feat: add nodelookup
- add helper script to make quering puppetdb easier and more efficient
This commit is contained in:
@@ -0,0 +1,61 @@
|
||||
#!/usr/bin/env <%= @venv_path %>/bin/python
|
||||
import requests
|
||||
import sys
|
||||
import argparse
|
||||
import json
|
||||
|
||||
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):
|
||||
url = 'http://puppetdb:8080/pdb/query/v4/facts'
|
||||
response = requests.get(url, params={'query': query})
|
||||
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()
|
||||
Reference in New Issue
Block a user