Merge pull request 'neoloc/nodelookup_consul' (#2) from neoloc/nodelookup_consul into develop

Reviewed-on: https://git.query.consul/unkinben/puppet-prod/pulls/2
This commit is contained in:
Ben Vincent 2024-06-01 12:11:48 +10:00
commit 810ba9ddb7

View File

@ -24,22 +24,27 @@ def build_query(node=None, fact_name=None, match=None, show_role=False):
return json.dumps(["and"] + query_filters)
def query_puppetdb(query):
# Determine the correct SSL certificate path based on the OS
if os.path.exists('/etc/ssl/certs/ca-certificates.crt'): # Debian/Ubuntu
cert_path = '/etc/ssl/certs/ca-certificates.crt'
elif os.path.exists('/etc/pki/tls/cert.pem'): # RHEL/CentOS
cert_path = '/etc/pki/tls/cert.pem'
else:
raise FileNotFoundError("SSL certificate file not found.")
url = 'https://puppetdbapi.main.unkin.net/pdb/query/v4/facts'
response = requests.get(url, params={'query': query}, verify=cert_path)
url = 'http://puppetdbapi.service.consul:8080/pdb/query/v4/facts'
response = requests.get(url, params={'query': query})
process_response(response)
def process_response(response):
def process_response(response, count_only=False):
if response.status_code == 200:
for fact in response.json():
print(f"{fact['certname']} {fact['value']}")
try:
response_data = response.json()
except ValueError:
print("Error decoding JSON response")
return
if count_only:
fact_counter = Counter(fact['value'] for fact in response_data)
for fact_value, count in fact_counter.items():
print(f"{fact_value}: {count}")
else:
facts = [f"{fact['certname']} {fact['value']}" for fact in response_data]
facts.sort()
for fact in facts:
print(fact)
else:
print(f"Error querying PuppetDB: HTTP {response.status_code}")
print("Response content:", response.text)
@ -54,6 +59,7 @@ def main():
parser.add_argument("-R", "--role", action="store_true", help="Show the role for matched hosts")
parser.add_argument("-F", "--fact", help="Specify a fact name")
parser.add_argument("-m", "--match", help="Simple pattern match for the value")
parser.add_argument("-C", "--count", action="store_true", help="Show count of rows with the same fact")
args = parser.parse_args()