Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python script to update host using Foreman's API

I want to write a script in Python that given two parameters, host & hostgroup, changes the the host's hostgroup using the Foreman API (http://theforeman.org/api/apidoc/v1/hosts/update.html).

The cURL command to do it, it's the following (it works!):

curl -s -H "Accept:application/json" -X PUT --insecure --negotiate -u : -d "host[hostgroup_id]=ZZZZZ" https://foreman.mydomain.com:443/api/hosts/XXXX

But now, I want to use a Python script to do it.

I'm using the Python request library without problems until I get to the part when I have to pass the parameter.

I am following this info http://docs.python-requests.org/en/latest/user/quickstart/#passing-parameters-in-urls but apparently this is not working because this is not the way that Foreman's API expects to receive the parameter.

So, any ideas how can I pass the parameter in a way that Foreman can understand?

Thanks in advance any help will be appreciated!

like image 991
dafero Avatar asked Jul 15 '14 16:07

dafero


2 Answers

Sorry, I found out the way to do it but I forgot to post it. The next code would do the trick:

def updateHost(host_id, new_hostgroup_id):
    url = "https://foreman.mydomain.com:443/api/hosts/" + host_id
    payload = {'host[hostgroup_id]': new_hostgroup_id}
    headers = {'Accept': 'application/json'}
    r = requests.put(url, data=payload, headers=headers, verify=False, uth=HTTPKerberosAuth())
    if (r.status_code != requests.codes.ok):
        raise BadStatusCodeRequest("HTTP Request status code error: " + r.raise_for_status())
like image 112
dafero Avatar answered Nov 16 '22 22:11

dafero


Make sure to know whether you are using v1 or v2 of theForeman API / also you might want to look at using Hammer if that is an option for you.

Using CURL, syntax to create a new host on Foreman using API (using RHOS) would look like:

curl -i -X POST POST -H "Content-Type: application/json" -d "{\"host\": {\"operatingsystem_id\": \"2\", \"r: \"10.0.0.20\", \"mac\": \"52:53:00:1e:69:69\", \"domain_id\": \"1\", \"puppet_proxy_id\": \"1\", \"name\": \"testhost1\", \"medium_id\": \"7\", \"architecture_id\": \"1\", \"ptable_id\": \"12\"}}" --user youradminuser:youradminpassword http://yourhostname.openhealthmodel.com/api/hosts

See theForeman api v2

Specifically GET vs. POST on HOST vs HOSTGROUP : you can iterate your existing hosts like this:

curl -X GET -H "Content-Type:application/json" -H "Accept: application/json" --user youradminuser:youradminpassword http://yourhostname.openhealthmodel.com/api/hosts

like image 38
MarkChristopherWest Avatar answered Nov 16 '22 23:11

MarkChristopherWest