Start AWX Job Via API
If you are using Ansible, there is high change you are also using AWX (or Ansible Tower) to orchestrate your jobs. And you might want trigger AWX jobs externally in some cases, such as from your CI pipeline. Luckily, AWX has an API that allows you to do just that.
To run AWX jobs remotely, you will need to make 3 API calls. One to start the job itself, another one to monitor its progress and lastly a request to print the output. You can see sample code to do that in bash shell below. In order to keep things simple, it uses authentication token, but you could also use OAuth 2.
POLLING_SLEEP=30 function print_job_output() { api_request GET "/jobs/${id}/stdout/?format=txt" } response=$( curl -s -i -o - "${AWX_API}/job_templates/${TEMPLATE_ID}/launch/" \ -H "Authorization: Bearer ${API_TOKEN}" \ -H "Content-Type: application/json" \ -XPOST ) http_status=$(head -n 1 <<<"${response}" | awk '{print $2}') body=$(grep '^{' <<<"${response}") if [[ ${http_status} != 201 ]]; then echo "AWX returned error." exit 1 fi id=$(jq <<<"${body}" '.id') echo "Monitoring job ID: ${id}" while true; do echo "Sleeping for ${POLLING_SLEEP}s" sleep $POLLING_SLEEP response="$(api_request GET "/jobs/${id}/" -i)" http_status=$(head -n 1 <<<"${response}" | awk '{print $2}') body=$(grep '^{' <<<"${response}") if [[ ${http_status} != 200 ]]; then echo "AWX returned error." exit 1 fi status="$(jq -r '.status' <<<"${body}")" if [[ "${status}" == "failed" ]]; then echo "Job failed." print_job_output exit 1 elif [[ "${status}" == "successful" ]]; then echo "Job has finished successfully." print_job_output exit 0 fi done