71 lines
2.4 KiB
Plaintext
71 lines
2.4 KiB
Plaintext
#!/usr/bin/env <%= @venv_path %>/bin/python
|
|
import requests
|
|
import sys
|
|
import argparse
|
|
import json
|
|
import os
|
|
|
|
def build_query(node=None, fact_name=None, match=None, show_role=False):
|
|
query_filters = []
|
|
|
|
if node:
|
|
query_filters.append(["=", "certname", node])
|
|
if fact_name:
|
|
query_filters.append(["=", "name", fact_name])
|
|
elif show_role:
|
|
query_filters.append(["=", "name", "enc_role"])
|
|
|
|
if match:
|
|
query_filters.append(["~", "value", match])
|
|
|
|
if not query_filters:
|
|
return '["=", "name", "enc_role"]'
|
|
else:
|
|
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)
|
|
process_response(response)
|
|
|
|
def process_response(response):
|
|
if response.status_code == 200:
|
|
for fact in response.json():
|
|
print(f"{fact['certname']} {fact['value']}")
|
|
else:
|
|
print(f"Error querying PuppetDB: HTTP {response.status_code}")
|
|
print("Response content:", response.text)
|
|
|
|
def parse_stdin():
|
|
for line in sys.stdin:
|
|
yield line.split()[0]
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description="Query PuppetDB for nodes.")
|
|
parser.add_argument("-n", "--node", help="Node name or partial match")
|
|
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")
|
|
|
|
args = parser.parse_args()
|
|
|
|
if not args.node and not sys.stdin.isatty():
|
|
for node in parse_stdin():
|
|
args.node = node
|
|
query = build_query(node=args.node, fact_name=args.fact, match=args.match, show_role=args.role)
|
|
query_puppetdb(query)
|
|
else:
|
|
query = build_query(node=args.node, fact_name=args.fact, match=args.match, show_role=args.role)
|
|
query_puppetdb(query)
|
|
|
|
if __name__ == "__main__":
|
|
main()
|