feat: add sort and count to node_lookup

- add -C option to count number of identical records
- sort responses from node_lookup
This commit is contained in:
Ben Vincent 2024-06-01 12:09:53 +10:00
parent 91e3f2d427
commit 7cf2e78cea

View File

@ -28,10 +28,23 @@ def query_puppetdb(query):
response = requests.get(url, params={'query': query}) response = requests.get(url, params={'query': query})
process_response(response) process_response(response)
def process_response(response): def process_response(response, count_only=False):
if response.status_code == 200: if response.status_code == 200:
for fact in response.json(): try:
print(f"{fact['certname']} {fact['value']}") 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: else:
print(f"Error querying PuppetDB: HTTP {response.status_code}") print(f"Error querying PuppetDB: HTTP {response.status_code}")
print("Response content:", response.text) print("Response content:", response.text)
@ -46,6 +59,7 @@ def main():
parser.add_argument("-R", "--role", action="store_true", help="Show the role for matched hosts") 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("-F", "--fact", help="Specify a fact name")
parser.add_argument("-m", "--match", help="Simple pattern match for the value") 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() args = parser.parse_args()