Skip to content

Instantly share code, notes, and snippets.

@bzed
Created August 31, 2021 07:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bzed/88c806e021ce26fc41ec77f8388124ea to your computer and use it in GitHub Desktop.
Save bzed/88c806e021ce26fc41ec77f8388124ea to your computer and use it in GitHub Desktop.
Export foreman smartvariables to yaml / for hiera
#!/usr/bin/python3
import requests
import os
from pprint import pprint
import functools
import yaml
USERNAME='username'
PASSWORD='password'
CERT=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'ca.pem')
PER_PAGE=99999999999999999
# curl -k -u username:password -H 'Accept:application/json,version=2' https://foreman_server/api/puppetclasses
# curl -k -u username:password -H 'Accept:application/json,version=2' https://foreman_server/api/environments/dev/puppetclasses/305/smart_class_parameters
def _apiurl(api: str) -> str:
return f'https://foreman.srv.conova.net/api/{api}'
def apirequest(api: str, params = {}):
s = requests.Session()
s.auth = (USERNAME, PASSWORD)
s.verify = CERT
params |= { 'per_page': PER_PAGE }
r = s.get(_apiurl(api), params = params)
return r.json()['results']
#classes = apirequest('puppetclasses')
#classes = functools.reduce(lambda x, y: x+y, classes.values())
#classes = functools.reduce(lambda x, y: x | { y['id'] : y['name'] }, classes, {})
# hosts = apirequest('hosts')
# pprint(hosts)
# hosts = functools.reduce(lambda x, y: x | { y['id'] : y['name'] }, hosts, {})
smart_class_parameters = apirequest('smart_class_parameters')
used_smart_class_parameters = [ x for x in smart_class_parameters if x['override_values_count'] > 0 ]
smart_class_overrides = {}
for scp in used_smart_class_parameters:
scp_id = scp['id']
overrides = apirequest(f'smart_class_parameters/{scp_id}/override_values')
overrides = [ x for x in overrides if not x['omit']]
if not overrides:
continue
parameter = f"{scp['puppetclass_name']}::{scp['parameter']}"
for override in overrides:
match = override['match']
if match not in smart_class_overrides:
smart_class_overrides[match] = {}
smart_class_overrides[match][parameter] = override['value']
yaml_smart_class_overrides = { x: yaml.dump(y) for x, y in smart_class_overrides.items() }
template = """
-------- %s ---------------------------------------------
%s
"""
output = ''.join([ template % (x,y) for x, y in yaml_smart_class_overrides.items() ])
print(output)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment