Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

- 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

>Solution :

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"}}'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading