Home > Blockchain >  How to pass variable data through Ansible Tower API to a playbook template
How to pass variable data through Ansible Tower API to a playbook template

Time:11-11

We use Ansible Tower for Operations to perform process restarts. If they receive an alert says a process stopped, they execute an Ansible Tower job and supply the host name and process name from the alert as "survey" variables. [A lot more happens, we don't just blindly restart every failure.]

I want to automate this with python by taking the host name and process name from the alert, and calling the Tower template. And I want to pass the host and process name as "-e" variables, but I cannot find any documentation on how to code the "extra_vars" in python.

The portion of the playbook with the service variable looks like:

- name: Check "{{ service }}"
  shell: systemctl status "{{ service }}".service | grep Active | awk -v N=2 '{print $N}'
  register: output
  tags: always

- name: Start "{{ service }}"
  service:
    name: "{{ service }}"
    state: started
  when: output.stdout == 'inactive'
  tags: start

The relevant part of the python3 code looks like:

headers = {'Content-Type': 'application/json'}
data = see below, this is where I am stuck
response = requests.post('http://localhost/api/v2/job_templates/13/launch/', headers=headers, data =data, verify=False, auth=('user','pass')

I have tried:

data = '{"service":"apache2"}'
data = '{"variables":["service","apache2"]}
data = '{"extra_vars":["service","apache2"]}

And these all fail cause the request to fail with a 400 response.

There seem to be answers in stackoverflow for using VariableManager(), but that method seems to bypass Tower and the existing templates.

Any thoughts on how I pass "extra_vars"?

Thanks

CodePudding user response:

Per https://docs.ansible.com/ansible-tower/latest/html/towerapi/api_ref.html#/Job_Templates/Job_Templates_job_templates_launch_create, Tower expects variables as extra_vars in the JSON body.

This attempt is the closest:

data = '{"extra_vars":["service","apache2"]}

however, you formatted it as a list of strings for some reason, instead of using the standard representation of variables as a dictionary/mapping.

data = '{"extra_vars": {"service": "apache2"}}'

CodePudding user response:

Found it.

I kept running "curl" commands, trying to populate the "service" variable and got this error: "variables_needed_to_start value missing" and when I googled that I found the syntax in the Ansible docs: (https://docs.ansible.com/ansible-tower/latest/html/userguide/job_templates.html#extra-variables)

body = '{"extra_vars": {"variable":"value"}}'

Thanks

  • Related