How to associate default templates to an OS in Foreman 1.15.6?

226 views Asked by At

I am using Foreman 1.15.6.

I created an OS using the below payload. However, the templates are not associated with the OS. So, I had to manually associate the templates in Foreman UI.

The REST API doc https://www.theforeman.org/api/1.15/index.html does not show any parameters to set the default templates for an OS.

How to set default templates using REST API ?

I am using the below JSON payload for creating OS

{
    "operatingsystem": {
        "name": "redhat7.5",
        "major": 7,
        "family": "Redhat",
        "architecture_ids": [1],
        "medium_ids": [1],
        "ptable_ids": [1],
        "provisioning_template_ids": [11, 20]                
    }
}   
1

There are 1 answers

0
Tejaswi On BEST ANSWER

The Foreman API documentation is not really helpful.

I used the hammer set-default-template in verbose mode to find the REST API call.

Below is the sample code to set the default templates for an OS using REST API

import requests
requests.packages.urllib3.disable_warnings()


FOREMAN_URL = 'https://192.168.10.20/api'
FOREMAN_CREDENTIALS = ('admin', 'foreman')

HEADERS = {'content-type': 'application/json'}


def get_template_by_id(template_id):
    url = '{}/{}/{}'.format(FOREMAN_URL, "config_templates", template_id)
    template = requests.get(url, auth=FOREMAN_CREDENTIALS, verify=False)
    return template.json()

def set_os_default_templates(os_id, template_ids):
    for template_id in template_ids:
        template = get_template_by_id(template_id)
        url = '{}/{}/{}/{}'.format(FOREMAN_URL, "operatingsystems", os_id, "os_default_templates")
        payload = {"os_default_template": {"config_template_id": str(template_id), "template_kind_name":template['template_kind_name']}}
        requests.post(url, headers=HEADERS, auth=FOREMAN_CREDENTIALS, json=payload, verify=False)

# Set templates with ids 10, 20 as default templates to OS with id 1        
os_id = 1
template_ids = (10, 20)
set_os_default_templates(os_id, template_ids)