Skip to content

Instantly share code, notes, and snippets.

@ekohl
Last active February 17, 2016 13:51
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 ekohl/58d97e3c4d3f8394c0d1 to your computer and use it in GitHub Desktop.
Save ekohl/58d97e3c4d3f8394c0d1 to your computer and use it in GitHub Desktop.
A simple script to override parameters through the foreman API
from __future__ import print_function
import json
import requests
class Foreman(object):
def __init__(self, session, base_url):
self.session = session
self.base_url = base_url
def get_variable(self, class_name, parameter):
url = '{}smart_class_parameters/'.format(self.base_url)
params = {'search': 'puppetclass={} and key={}'.format(class_name, parameter)}
response = self.session.get(url, params=params)
response.raise_for_status()
result = response.json()
try:
return result['results'][0]
except IndexError:
return None
def get_variable_overrides(self, variable_id, value=None, per_page=100, page=1):
# TODO: Search doesn't work - http://projects.theforeman.org/issues/13517
url = '{}smart_class_parameters/{}/override_values'.format(self.base_url, variable_id)
response = self.session.get(url)
response.raise_for_status()
result = response.json()
for override in result['results']:
if not value or override['value'] == value:
yield override
if int(result['subtotal']) > page * per_page:
for variable in self.get_variable_overrides(variable_id, value, per_page, page + 1):
yield variable
def change_override(self, variable_id, override_id, new_value):
url = '{}smart_class_parameters/{}/override_values/{}'.format(self.base_url, variable_id, override_id)
# TODO: Newer versions of requests can do json= instead of data= + headers=
data = json.dumps({'override_value': {'value': new_value}})
response = self.session.put(url, data=data, headers={'Content-Type': 'application/json'})
response.raise_for_status()
def main():
class_name = 'apache'
parameter_name = 'apache_name'
old_value = 'test2'
new_value = 'test'
session = requests.Session()
session.auth = ('user', 'password')
session.verify = False # TODO
base_url = 'https://foreman.example.com/api/'
foreman = Foreman(session, base_url)
print('Searching for variable')
variable = foreman.get_variable(class_name, parameter_name)
if not variable:
print('Failed to find variable')
raise SystemExit(1)
print('Searching for overrides')
overrides = foreman.get_variable_overrides(variable['id'], old_value)
for override in overrides:
print('Changing', override['match'], 'to', new_value)
foreman.change_override(variable['id'], override['id'], new_value)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment