This is a short example how you interact from an ansible playbook with a rest api.
The start#
The example doesn`t use the credential store of ansible tower or an ansible vault which is not best practice this is only for demo purposes, api_user and api_pass should be feeded from ansible tower credential store.
The 4 other variables (os, site, zone, scope) can be feeded by a survey in ansible tower when the playbook will be started.
---
- name: Testplaybook
hosts: localhost
connection: local
gather_facts: False
vars:
api_user: automation
api_pass: supersecret
os: unix
site: munich
zone: dmz
scope: server
Aquire token from authentication server#
To recieve a token you must do a POST against the auth interface with the credentials, the authentication server response with HTTP Code 200 and deliver in the body a JWT web token_content. The output is stored in the token variable. The second task extract the token out of the json response and store it in the variable token for easier use. The token has per default a validity of 3600 seconds.
tasks:
- name: Acquire token
uri:
url: http://auth.m.lab/api/v1/auth
method: POST
body:
username: "{{ api_user }}"
password: "{{ api_pass }}"
body_format: json
status_code: 200
register: token_content
- name: Set token fact
set_fact:
token: "Bearer {{ token_content.json.token }}"
Make a request against the rest api#
You can see that all variables are used in the body section. Here you build your dictionaries and lists, with the parameter body_format: json you advise ansible to set the format to json. In the header section you set the stored token for authorization. You register the output of the call in job_id. In the next step you will call the middleware and ask if the job is finished or not.
- name: Flux IP and Hostname
uri:
url: "http://api.m.lab/dns/api/v1/flux_ip_and_hostname"
body:
os: "{{ os }}"
zone: "{{ zone }}"
scope: "{{ scope }}"
site: "{{ site}}"
body_format: json
method: POST
headers:
Authorization: "{{ token }}"
register: job_id
- name: Set job_id fact
set_fact:
job_idx: "{{ job_id.json.job_id }}"
Check if the job is finished#
Now you can ask the rest api with the job_id if the job is completed or not. Here is a until loop implemented, ansible will start the task again and again until the result is result.json.status == “ok” or the max. delay (10 retries * 5 sec delay = max. 50 seconds) is reached. In case of the call is not successful the playbook stop in the condition failed.
- name: Wait until ip and hostname are created
uri:
url: "http://api.m.lab/dns/api/v1/results/{{ job_idx }}"
method: GET
headers:
Authorization: "{{ tokenx }}"
register: result
until: result.json.status == "ok"
retries: 10
delay: 5
- name: Register new ip and hostname to work with
set_fact:
new_vm_ddi_data: "{{result.json.result.data}}"
Final task work with the output#
- name: Output
debug:
var: new_vm_ddi_data