Extracting Data from the Ansible Tower API
Ansible Tower exposes a comprehensive RESTful API. In fact, Tower is first implemented as an API and then the UI is written to consume that API; anything that can be done from the UI can also be done by making calls to the API. In this article I will show you how to use this API to extract job information from Tower. As a sample use case, we’re going to capture details about specific jobs and store them externally to Tower. This sort of use case might come up as part of storing jobs for an audit purpose.
It’s easy to get started with the Tower API and there is documentation for the API running right alongside the API. If you have access to a Tower deployment you can find a browsable API by going to https://{your_tower_hostname}/api/v2 On this page you can browse the API and interact directly with the API from your browser. In our sample use case, we want to find and extract data related to jobs.
To do this we will first need to query for a list of jobs. We can do that by first quering the /api/v2/jobs/ endpoint. This endpoint contains information about all jobs that have been executed on the Tower node. In the sample code below, we simply iterate over every single job that has been executed on the node and then save the job IDs into a list. From there we can iterate over that list and query the /api/v2/jobs/{job_id}/job_events/ endpoint to gather data about the executed job. From there we can write this information to an archive for storage.
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
# Defining tower host, user and password #IMPROVE
tower_username = 'apiuser'
tower_password = 'apiuserpassword'
tower_url = 'https://tower.demo.com'
request_url = tower_url + '/api/v2/jobs/'
# Instantiate an empty array to hold Job IDs
jobs = []
# Create a list of all Job IDS
# Get initial list, and keep going through the job list as long as 'next' is defined
while(True):
response = requests.get(request_url, auth=(tower_username, tower_password), verify=False)
jsonResponse = response.json()
for job in jsonResponse["results"]:
jobs.append(job["id"])
if (jsonResponse["next"] == None):
break
else:
request_url = tower_url + jsonResponse["next"]
# Iterate over the Job IDS to get events
for jobid in jobs:
request_url = tower_url + '/api/v2/jobs/' + str(jobid) + '/job_events/'
response = requests.get(request_url, auth=(tower_username, tower_password), verify=False)
jsonResponse = response.json()
# Iterate over tasks
for task in jsonResponse["results"]:
print('do something for the tasks')

