Python script to update host using Foreman's API

curl, httprequest, kerberos, python, theforeman

Solution

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())

Problem

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!

Original source