Until now, whenever Aurora Store has run a playbook, it's been launched by a person in a terminal, by CI (which launches AWX with awx, Lesson 8.3) or by AWX with its interface and its schedules. But sooner or later the need arises to launch Ansible from a program of your own: an internal portal where the Development team asks for "update the packages on web2", a chat bot, a maintenance tool that decides which servers to reboot based on what happened in each task. The temptation is to import Ansible's classes from Python and call them directly. In this lesson you'll see why that's a bad idea and you'll get to know the two stable alternatives: ansible-runner, the library used internally by AWX, ansible-navigator and Event-Driven Ansible, which runs playbooks and hands you every event of the run; and the AWX REST API, which launches existing templates with all the control of the platform. You'll write a small Aurora tool with each of them and finish with a table for choosing between them.

Contents

  1. Launching Ansible from a program
  2. Why not use Ansible's internal Python API?
  3. ansible-runner: what it is and who uses it
  4. Installation
  5. The private data directory (private_data_dir)
  6. ansible-runner run from the command line
  7. The Python interface: ansible_runner.run()
  8. Events, status and callbacks
  9. An Aurora tool: tools/update.py
  10. Background runs: run_async
  11. How AWX uses ansible-runner
  12. The AWX REST API
  13. awx, awx.awx and the API: the same platform, three doors
  14. Which option to choose?

  1. Launching Ansible from a program

Real cases in which a program (not a person) launches Ansible:

Case Example in Aurora
Self-service portal Development asks to restart the staging catalog API from an internal website
ChatOps A message in the Operations channel launches the configuration check
Maintenance tool Upgrading packages and deciding, based on the result for each host, which ones need a reboot
Reacting to events A monitoring alert triggers a remediation (Lesson 10.5)
Tests Launching a playbook and checking its result from pytest

The naive approach is to run ansible-playbook with subprocess and read its output or its return code. That's fine for the basics (0 = OK, 2 = failures, 4 = unreachable, Lesson 3.1), but the output is designed for people: extracting from it which task failed on which host, or the value a module returned, is fragile. You need something more structured.

  1. Why not use Ansible's internal Python API?

Ansible is written in Python, so it's possible to import its classes (DataLoader, InventoryManager, VariableManager, PlaybookExecutor, TaskQueueManager…) and put together a run from your code. There are examples on the Internet, and Ansible's own documentation shows one. But that same documentation warns that this API is for internal use and may change in any release without preserving compatibility. In practice:

Problem Consequence
It's neither a public nor a stable API Every ansible-core upgrade can break your program (versions 2.19 and later changed the templating engine and the internal data a great deal)
Your program shares a process with Ansible A crash, a memory leak or a global configuration change affects both; Ansible assumes it owns the process (signals, fork of the workers, global configuration variables)
You have to reimplement what ansible-playbook does Reading ansible.cfg, loading callbacks, Vault passwords, command-line options…
No isolation You can't easily run in an EE or limit resources

That's why the project's own recommendation is: don't import Ansible; run it, with a tool designed for the purpose. That tool is ansible-runner.

  1. ansible-runner: what it is and who uses it

ansible-runner is a tool and a Python library that:

  • Runs ansible-playbook (or ansible, or any other Ansible command) as a separate process, optionally inside a container (an EE).
  • Installs its own callback in that run to capture every event (a play starts, a task finishes on a host…) as a structured JSON document.
  • Organizes the inputs (inventory, variables, passwords, keys) and the outputs (standard output, events, return code, status) in a directory with a fixed structure.
  • Offers a stable interface, on the command line and in Python, with its own versions and maintained compatibility.

You've already used it without knowing:

flowchart TB
    R[ansible-runner]
    AWX[AWX / automation controller<br/>Module 7] --> R
    NAV[ansible-navigator<br/>Lesson 7.6] --> R
    EDA[ansible-rulebook / EDA<br/>Lesson 10.5] --> R
    TU[Your tools<br/>this lesson] --> R
    R --> AP[ansible-playbook<br/>in a process or in an EE]

It even appears in the aurora-ee definition (dependencies.ansible_runner, Lesson 7.6): AWX needs it inside the EE to run jobs.

  1. Installation

ansible-runner needs to find ansible-playbook in the PATH. The simplest approach is to install it in the project's .venv (Lesson 9.4), which already has ansible-core 2.17. Add to ci/requirements.txt:

ansible-runner==2.4.1

The version is just an example: check the latest release and pin it, like the rest of the tools in the file. Install it and activate the environment in the terminal you'll be working in:

cd ~/aurora-infra
.venv/bin/pip install -r ci/requirements.txt
source .venv/bin/activate
ansible-runner --version
which ansible-playbook          # must be ~/aurora-infra/.venv/bin/ansible-playbook

source .venv/bin/activate puts .venv/bin at the start of the PATH (and deactivate undoes it). This matters: if ansible-runner found a different ansible-playbook (the pipx one, for example), it would run a different version of Ansible without telling you.

  1. The private data directory (private_data_dir)

ansible-runner works on a directory with an agreed structure, the private data dir. All its parts are optional:

private_data_dir/
├── env/
│   ├── extravars        extra variables (YAML or JSON), like -e
│   ├── passwords        answers to interactive prompts (regular expression → answer)
│   ├── envvars          environment variables for the run (YAML or JSON)
│   ├── settings         runner settings: job_timeout, idle_timeout, process_isolation...
│   ├── cmdline          extra options for ansible-playbook (text: "--diff --tags deploy")
│   └── ssh_key          SSH private key (runner loads it into a temporary ssh-agent)
├── inventory/           inventory (file or directory)
├── project/             playbooks, roles... (the "project")
└── artifacts/           OUTPUTS: one folder per run
    └── <ident>/
        ├── command      the exact command that was run
        ├── rc           return code
        ├── status       successful, failed, timeout or canceled
        ├── stdout       the full output
        ├── job_events/  one JSON file per event
        └── fact_cache/  gathered facts (if the runner cache is used)

It's exactly what AWX prepares for every job: it writes the credentials to env/ and ssh_key, the synced inventory to inventory/, the project to project/, and reads the events from artifacts/.

Security: env/passwords, env/ssh_key and the artifacts (the output may contain sensitive data not protected with no_log) are sensitive material. Create the directory with 0700 permissions and never put it in the repository.

  1. ansible-runner run from the command line

A minimal example, outside aurora-infra, to see the structure in action:

mkdir -p -m 700 ~/runner-demo/{env,inventory,project}

cat > ~/runner-demo/inventory/hosts <<'EOF'
localhost ansible_connection=local
EOF

cat > ~/runner-demo/env/extravars <<'EOF'
---
greeting: Hello from ansible-runner
EOF

cat > ~/runner-demo/project/hello.yml <<'EOF'
---
- name: Say hello
  hosts: all
  gather_facts: false
  tasks:
    - name: Show the greeting
      ansible.builtin.debug:
        msg: "{{ greeting }}"
EOF

ansible-runner run ~/runner-demo -p hello.yml
  • run runs and waits for it to finish. Other actions: start (in the background), is-alive and stop.
  • -p hello.yml: the playbook, relative to project/.
  • The on-screen output is the usual one. The interesting part is in artifacts/:
ls ~/runner-demo/artifacts/
ls ~/runner-demo/artifacts/*/
cat ~/runner-demo/artifacts/*/status ~/runner-demo/artifacts/*/rc
ls ~/runner-demo/artifacts/*/job_events/ | head
command  fact_cache  job_events  rc  status  stdout
successful
0
1-0d8d3c2b-....json
2-5f1e9a04-....json
...

Each file in job_events/ is one event in JSON, numbered in order. If you'd rather have the events in the output itself (to process them with jq, for example), use -j (--json): each line will be an event.

ansible-runner run ~/runner-demo -p hello.yml -j | jq -r 'select(.event == "runner_on_ok") | .event_data.res.msg'
# Hello from ansible-runner

Each run creates a new folder in artifacts/ (named with a unique identifier, which you can set with --ident). With --rotate-artifacts 10, only the last ten are kept. Delete the demo when you're done: rm -rf ~/runner-demo.

  1. The Python interface: ansible_runner.run()

The same run, from Python:

import ansible_runner

r = ansible_runner.run(private_data_dir='/home/student/runner-demo', playbook='hello.yml')

print(r.status)   # 'successful'
print(r.rc)       # 0
print(r.stats)    # {'ok': {'localhost': 1}, 'changed': {}, 'failures': {}, 'dark': {}, ...}

for event in r.events:
    if event['event'] == 'runner_on_ok':
        print(event['event_data']['host'], event['event_data']['res'].get('msg'))

run() accepts, as arguments, almost everything the data directory offers as files. The most useful:

Argument Equivalent to Example
private_data_dir The working directory (mandatory) '/home/student/.cache/aurora-infra/runner'
project_dir project/, but at another path '/home/student/aurora-infra'
playbook -p 'playbooks/upgrade.yml'
inventory inventory/ or -i (path or content) '/home/student/aurora-infra/inventories/lab'
limit, tags, skip_tags, verbosity, forks The ansible-playbook options limit='web2'
extravars env/extravars {'aurora_app_version': '1.4.0'}
envvars env/envvars {'ANSIBLE_FORCE_COLOR': 'false'}
cmdline env/cmdline '--check --diff'
quiet Don't show Ansible's output on screen True
rotate_artifacts --rotate-artifacts 10
ident Name of the artifacts folder 'update-web2'
event_handler, status_handler, finished_callback, cancel_callback Functions runner calls during the run (section 8)
process_isolation, container_image Run inside a container container_image='registry.../aurora-ee:1.4.0'

The returned object (a Runner) offers:

Attribute Content
status 'successful', 'failed', 'timeout' or 'canceled'
rc ansible-playbook's return code
stats The PLAY RECAP counters per host: ok, changed, failures, dark (unreachable), skipped, rescued, ignored, processed
events An iterator over all the events
stdout The full output (an open file: r.stdout.read())
config.artifact_dir Path of this run's artifacts folder
get_fact_cache(host) A host's facts, if they were gathered

  1. Events, status and callbacks

8.1. The structure of an event

Each event is a dictionary. The common fields:

Field Content
event Event type
counter Sequence number
stdout The text that event produced in the output
created Date and time
event_data The event data (depends on the type)

And the most useful types, which you'll recognize from the v2_* methods of the callback in Lesson 10.3 (they're the same event, seen from outside):

event When Useful event_data
playbook_on_start The playbook starts playbook
playbook_on_play_start A play starts play, play_pattern
playbook_on_task_start A task starts task, task_action
runner_on_ok Task succeeded on a host host, task, res (the module's JSON), duration
runner_on_failed Task failed on a host host, task, res, ignore_errors
runner_on_skipped Task skipped host, task
runner_on_unreachable Host unreachable host, res
playbook_on_stats End, with the summary ok, changed, failures, dark… per host

The res field is what Ansible would return in a register: in the runner_on_ok of a stat task, res['stat']['exists']. That's the big advantage over reading the output: you have the data of each result, not its text representation.

8.2. runner's callback functions

Instead of iterating over r.events at the end, you can react while it runs:

Argument Called Signature
event_handler With each event function(event); if it returns True, the event is saved in artifacts/; with False, it's discarded
status_handler When the status changes (starting, running, successful…) function(status_data, runner_config)
finished_callback When it finishes function(runner)
cancel_callback Periodically; if it returns True, it cancels the run function()

Don't confuse these runner callbacks (functions in your program) with Ansible's callback-type plugins (Lesson 10.3). In fact, runner obtains the events thanks to a callback plugin of its own that it installs in the run, and then passes them on to your functions.

  1. An Aurora tool: tools/update.py

9.1. The goal

playbooks/upgrade.yml (Lessons 5.8 and 9.3) upgrades packages and reports, with a debug, which servers need a reboot, but it doesn't reboot them: someone has to read the output. The team wants a tool to use in the terminal and, later on, from other programs, that:

  • Requires a --limit (never upgrade everything by accident).
  • Shows one readable line per host and task as it progresses.
  • At the end, gives a structured summary (optionally in JSON): status, hosts with changes, hosts that need a reboot and errors.
  • Ends with an exit code that's useful to other programs: 0 all good, 2 good but with pending reboots, 1 failures.

9.2. The code

Create the tools/ directory in aurora-infra and, inside it, update.py:

#!/usr/bin/env python3
"""Upgrade the packages of Aurora Store servers with ansible-runner.

Runs playbooks/upgrade.yml and summarizes which servers have changed, which
need a reboot and which have failed.

Usage (with the project's .venv activated):
  python tools/update.py --limit web2
  python tools/update.py --limit webservers --json

Exit codes: 0 = success, 2 = success with pending reboots, 1 = failures.
"""
import argparse
import json
import os
import sys

import ansible_runner

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DATA = os.path.expanduser('~/.cache/aurora-infra/runner')
REBOOT_TASK = 'Check whether the system needs a reboot'


def main():
    parser = argparse.ArgumentParser(description='Upgrade the packages of Aurora Store servers.')
    parser.add_argument('--limit', required=True, help='Hosts or groups to upgrade (mandatory).')
    parser.add_argument('--inventory', default='inventories/lab',
                        help='Inventory, relative to the repository root (the lab by default).')
    parser.add_argument('--json', action='store_true', help='Show only a final summary in JSON.')
    args = parser.parse_args()

    reboots = []
    errors = []

    def on_event(event):
        kind = event.get('event')
        data = event.get('event_data', {})
        host = data.get('host')

        if kind == 'runner_on_ok' and data.get('task') == REBOOT_TASK:
            if data.get('res', {}).get('stat', {}).get('exists'):
                reboots.append(host)
        elif kind == 'runner_on_failed' and not data.get('ignore_errors'):
            message = data.get('res', {}).get('msg', '')
            errors.append('%s: %s: %s' % (host, data.get('task'), message))
        elif kind == 'runner_on_unreachable':
            errors.append('%s: unreachable' % host)

        if not args.json and kind in ('runner_on_ok', 'runner_on_failed', 'runner_on_unreachable'):
            outcome = kind.replace('runner_on_', '')
            print('  %-10s %-12s %s' % (host, outcome, data.get('task')))
        return True

    def on_status_change(status, config):
        if not args.json:
            print('== %s' % status['status'])

    os.makedirs(DATA, mode=0o700, exist_ok=True)
    result = ansible_runner.run(
        private_data_dir=DATA,
        project_dir=ROOT,
        playbook='playbooks/upgrade.yml',
        inventory=os.path.join(ROOT, args.inventory),
        limit=args.limit,
        quiet=True,
        rotate_artifacts=10,
        event_handler=on_event,
        status_handler=on_status_change,
    )

    stats = result.stats or {}
    summary = {
        'status': result.status,
        'code': result.rc,
        'limit': args.limit,
        'with_changes': sorted(stats.get('changed', {})),
        'reboot_required': sorted(set(reboots)),
        'errors': errors,
        'artifacts': result.config.artifact_dir,
    }

    if args.json:
        print(json.dumps(summary, indent=2, ensure_ascii=False))
    else:
        print()
        print('Status:              %s' % summary['status'])
        print('With changes:        %s' % (', '.join(summary['with_changes']) or 'none'))
        print('Need a reboot:       %s' % (', '.join(summary['reboot_required']) or 'none'))
        for error in errors:
            print('ERROR: %s' % error)
        print('Artifacts:           %s' % summary['artifacts'])

    if result.status != 'successful':
        return 1
    if summary['reboot_required']:
        return 2
    return 0


if __name__ == '__main__':
    sys.exit(main())

9.3. Explanation

  • #!/usr/bin/env python3 and the docstring: they let you run it as a program and document the usage and the exit codes, the first thing anyone calling it from another program needs.
  • ROOT: the repository root, computed from the location of the file itself (tools/update.py → its directory → the parent directory). That way it works from any working directory.
  • DATA: the private_data_dir, outside the repository, in the user's cache (next to ~/.cache/aurora-infra/facts from Lesson 9.3), created with 0700 permissions.
  • argparse: the standard library for command-line options. required=True makes --limit mandatory; action='store_true' turns --json into a switch.
  • on_event: the event_handler. It's a function nested inside main(), so it can use args, reboots and errors directly (in Python, an inner function can modify the lists of the function that contains it).
    • To detect reboots, it looks for the runner_on_ok event of upgrade.yml's "Check whether the system needs a reboot" task and looks at res.stat.exists: the same data that aurora_reboot_required registers in the playbook. The chained .get(..., {}) calls avoid errors if a key is missing.
    • Failures with ignore_errors don't count, just as in the summary callback.
    • It returns True so that runner saves the event in artifacts/.
  • ansible_runner.run(...):
    • project_dir=ROOT: the project is aurora-infra itself, without copying anything. Runner runs ansible-playbook from that directory, so its ansible.cfg applies (role and collection paths, pipelining, fact cache, callbacks) and relative paths work, such as ssh/known_hosts.lab from Lesson 9.2.
    • inventory: the absolute path to the chosen inventory.
    • quiet=True: doesn't repeat Ansible's output on screen; we already show our own lines.
    • Your session's environment variables reach the run, including ANSIBLE_VAULT_IDENTITY_LIST (Lesson 9.1), which is needed because the plays load playbooks/group_vars/lab/vault.yml.
  • result.stats or {}: if the playbook doesn't even start (a syntax error), stats may be empty; or {} avoids an error.
  • sys.exit(main()): the value main() returns becomes the program's exit code.

9.4. Testing it

cd ~/aurora-infra
source .venv/bin/activate
chmod +x tools/update.py
python tools/update.py --limit web2
== starting
== running
  web2       ok           Upgrade all the system packages
  web2       ok           Check whether the system needs a reboot
  web2       ok           Report the servers that need a reboot
== successful

Status:              successful
With changes:        web2
Need a reboot:       web2
Artifacts:           /home/student/.cache/aurora-infra/runner/artifacts/2b0c...

(The exact result depends on the pending updates in your lab; you'd also see an event for the fact-gathering task if the playbook had one.) Check the exit code with echo $? and try the JSON output, which is what another program would consume:

python tools/update.py --limit web2 --json | jq .reboot_required

And a failure: python tools/update.py --limit nonexistent ends with a failed status… or does it? Try it: a --limit that matches no host makes ansible-playbook finish without an error and without doing anything. That's a good reason for Exercise 1.

Commit tools/update.py and ci/requirements.txt, and document the tool in the README.md ("Tools") and in CHANGELOG.md: "Tools: update.py with ansible-runner".

  1. Background runs: run_async

A web portal can't sit blocked for twenty minutes waiting for an upgrade. run_async takes the same arguments as run, but immediately returns a thread and the Runner object:

import time

import ansible_runner

thread, run = ansible_runner.run_async(
    private_data_dir='/home/student/.cache/aurora-infra/runner',
    project_dir='/home/student/aurora-infra',
    playbook='playbooks/upgrade.yml',
    inventory='/home/student/aurora-infra/inventories/lab',
    limit='web2',
    quiet=True,
)

while thread.is_alive():
    print('Status:', run.status)
    time.sleep(5)

print('Final:', run.status, run.rc)
  • thread.is_alive() is true for as long as the run lasts; meanwhile, your program can handle other requests.
  • run.status updates by itself.
  • To cancel from outside, use the cancel_callback (a function that returns True when you want to stop) or, on the command line, ansible-runner stop.

If the service that launches these runs grows (queues, multiple users, permissions, history), realize that you're rebuilding AWX. That's the moment to use AWX and its API (section 12).

  1. How AWX uses ansible-runner

sequenceDiagram
    participant U as User / API
    participant T as AWX (task)
    participant Rc as Receptor
    participant P as Job pod (EE aurora-ee)
    U->>T: Launch "Aurora - Check configuration"
    T->>T: Prepares the private_data_dir:<br/>project, inventory, credentials in env/
    T->>Rc: ansible-runner transmit (packages and sends)
    Rc->>P: ansible-runner worker (runs ansible-playbook)
    P-->>Rc: JSON events in a continuous stream
    Rc-->>T: ansible-runner process (receives the events)
    T->>T: Stores the events in PostgreSQL
    T-->>U: The job output appears in the interface in real time
  • transmit / worker / process are three ansible-runner modes designed to separate where the run is prepared, where it runs (the pod with the EE, perhaps on another node of the Receptor mesh, Lesson 7.1) and where the results are processed.
  • The events you see in an AWX job's output, with their JSON detail (Lesson 7.3), are exactly the runner events from section 8.
  • ansible-navigator (Lesson 7.6) uses runner to run inside the EE, and its playbook artifact is the collection of events.

Understanding runner therefore means understanding how AWX works internally.

  1. The AWX REST API

12.1. When it's better than runner

If the operation already exists as a template in AWX, launching it through the API has advantages that a program using runner doesn't:

Aspect With ansible-runner in your program With the AWX API
SSH and Vault credentials The machine your program runs on needs them AWX stores them; your program only needs a token
Permissions Whatever the program's account has AWX RBAC (Execute on the template)
Auditing Whatever you program Job history and Activity Stream
Execution environment The machine's The organization's EE (aurora-ee)
Custom logic on each event Complete, in real time Possible (by querying the job events), but less immediate

12.2. Authentication

AWX uses personal access tokens: in the interface, user → Tokens → add, with the Write scope (needed for launching). For a program, create a service user with the minimum permission, as you did with gitea-ci in Lesson 8.3 (Execute only on the templates it must launch). The token travels in the Authorization: Bearer <token> header and, like any secret, is kept in an environment variable or a secrets manager, never in the code.

12.3. The endpoints you need

Operation Method and path
Find a template by name GET /api/v2/job_templates/?name=<name>
Launch it POST /api/v2/job_templates/<id>/launch/ with an optional JSON body (limit, extra_vars, job_tags…)
Status of a job GET /api/v2/jobs/<id>/ (status field: pending, waiting, running, successful, failed, error, canceled)
Per-host summary GET /api/v2/jobs/<id>/job_host_summaries/
Events GET /api/v2/jobs/<id>/job_events/?event=runner_on_failed
Full output GET /api/v2/jobs/<id>/stdout/?format=txt
Cancel POST /api/v2/jobs/<id>/cancel/
Launch a workflow POST /api/v2/workflow_job_templates/<id>/launch/

The parameters you send at launch only apply if the template prompts for them on launch (Prompt on launch, Lesson 7.3); otherwise, AWX ignores them and lists them in the ignored_fields field of the response. Aurora - Check configuration prompts for the Limit.

With curl, to see the mechanics:

export AWX_HOST=http://192.168.56.30:30080
read -rs AWX_TOKEN && export AWX_TOKEN        # paste the token; it doesn't end up in the history

curl -s -H "Authorization: Bearer $AWX_TOKEN" \
  "$AWX_HOST/api/v2/job_templates/?name=Aurora%20-%20Check%20configuration" | jq '.results[0].id'

curl -s -X POST -H "Authorization: Bearer $AWX_TOKEN" -H "Content-Type: application/json" \
  -d '{"limit": "web1"}' "$AWX_HOST/api/v2/job_templates/<id>/launch/" | jq '{job, status}'

The name is URL-encoded (%20 is a space; any non-ASCII character would also be encoded, as a %XX sequence per byte).

12.4. The same tool, with the API: tools/awx_launch.py

A generic template launcher, using only Python's standard library (urllib), so that it works on any machine without installing anything:

#!/usr/bin/env python3
"""Launch an AWX template, wait for it to finish and summarize the result per host.

Usage:
  export AWX_HOST=http://192.168.56.30:30080
  export AWX_TOKEN=...        (token with Write scope; never in the code)
  python3 tools/awx_launch.py "Aurora - Check configuration" --limit web1
"""
import argparse
import json
import os
import sys
import time
import urllib.parse
import urllib.request

FINAL = ('successful', 'failed', 'error', 'canceled')


def api(method, path, data=None):
    url = os.environ['AWX_HOST'].rstrip('/') + path
    body = json.dumps(data).encode() if data is not None else None
    request = urllib.request.Request(url, data=body, method=method)
    request.add_header('Authorization', 'Bearer ' + os.environ['AWX_TOKEN'])
    request.add_header('Content-Type', 'application/json')
    with urllib.request.urlopen(request, timeout=30) as response:
        return json.loads(response.read())


def main():
    parser = argparse.ArgumentParser(description='Launch an AWX template.')
    parser.add_argument('template', help='Exact name of the template.')
    parser.add_argument('--limit', help='Host limit (the template must prompt for it on launch).')
    args = parser.parse_args()

    search = api('GET', '/api/v2/job_templates/?name=' + urllib.parse.quote(args.template))
    if search['count'] != 1:
        sys.exit('Cannot find the template "%s".' % args.template)
    template_id = search['results'][0]['id']

    data = {'limit': args.limit} if args.limit else {}
    launch = api('POST', '/api/v2/job_templates/%d/launch/' % template_id, data)
    if launch.get('ignored_fields'):
        print('Warning: AWX has ignored %s' % launch['ignored_fields'])
    job = launch['job']
    print('Job %d launched: %s/#/jobs/playbook/%d/output' % (job, os.environ['AWX_HOST'], job))

    status = None
    while status not in FINAL:
        time.sleep(5)
        status = api('GET', '/api/v2/jobs/%d/' % job)['status']
        print('  %s' % status)

    for summary in api('GET', '/api/v2/jobs/%d/job_host_summaries/' % job)['results']:
        print('%-8s ok=%-3d changed=%-3d failures=%-3d unreachable=%d' % (
            summary['host_name'], summary['ok'], summary['changed'],
            summary['failures'], summary['dark']))

    return 0 if status == 'successful' else 1


if __name__ == '__main__':
    sys.exit(main())
  • api() centralizes the request: it builds the URL, adds the token and the headers, sends the JSON (if any) and decodes the response. urllib.request.urlopen raises an exception if AWX responds with an error (401 without permission, 404…), which stops the program with a message.
  • urllib.parse.quote encodes the template name for the URL.
  • The search returns count and results; we require exactly one match.
  • After launching, it polls the status every 5 seconds until a final state. For a more reactive program, AWX can also notify you when it finishes, through webhook notifications (Lesson 7.3).
  • At the end, job_host_summaries gives the same counters as the PLAY RECAP (dark = unreachable).
python3 tools/awx_launch.py "Aurora - Check configuration" --limit web1

Commit it along with update.py.

  1. awx, awx.awx and the API: the same platform, three doors

The REST API is the foundation of everything else:

Tool What it is When to use it
REST API HTTP + JSON From any language; custom integrations
awx (awxkit) Command-line client on top of the API (Lessons 7.3 and 8.3) Shell scripts and CI: awx job_templates launch "..." --limit web1 --monitor
awx.awx collection Ansible modules on top of the API From a playbook: launching jobs or, above all, configuring AWX as code (templates, credentials, inventories)

An example with the collection (which Aurora does not have in collections/requirements.yml; if you wanted to use it, you'd add it there with a pinned version):

- name: Launch the configuration check in AWX
  hosts: localhost
  gather_facts: false
  tasks:
    - name: Launch the template
      awx.awx.job_launch:
        name: "Aurora - Check configuration"
        limit: web1
        wait: true
        timeout: 1800
        controller_host: "{{ lookup('ansible.builtin.env', 'AWX_HOST') }}"
        controller_oauthtoken: "{{ lookup('ansible.builtin.env', 'AWX_TOKEN') }}"
      register: aurora_awx_job

wait: true makes the task wait for the job to finish (with awx.awx.job_wait you can separate launching from waiting). Full configuration of AWX as code with this collection (having every template, credential and inventory from Module 7 in the repository) is a natural improvement you can consider in the final project.

  1. Which option to choose?

Need Recommended option
A script launches a playbook and only cares whether it went well ansible-playbook with subprocess (return code) or ansible-runner run
A program needs the data of each task and host, in real time ansible-runner (Python), like update.py
Running inside an EE from your program ansible-runner with process_isolation / container_image, or ansible-navigator
The operation is already an AWX template and you want centralized permissions, auditing and credentials AWX REST API, awx or awx.awx
Configuring AWX as code awx.awx
Importing PlaybookExecutor and friends No: an internal API with no compatibility guarantees

In Aurora, the rule of thumb: whatever is a routine team operation lives in AWX and is launched through its API (CI already does this); ansible-runner is for local tools that need to react to results, like update.py, and for understanding what AWX and EDA do internally.

Common Mistakes and Tips

  • ansible-runner uses a different ansible-playbook: if you don't activate the .venv, it may find the pipx one (a different version). Check with which ansible-playbook and, when in doubt, look at artifacts/<ident>/command.
  • Relative paths that don't work: inventory and private_data_dir must be absolute paths (os.path.join(ROOT, ...), os.path.expanduser).
  • Missing Vault passwords: the run inherits the environment; if you launch the tool from a system service (for example, systemd), that service doesn't have your ANSIBLE_VAULT_IDENTITY_LIST. Pass it with envvars or, better, use AWX.
  • Looking for results in stdout: use the events (res). The output changes with the callback, the language or the verbosity; the data doesn't.
  • A slow event_handler: it runs for every event; if it makes slow network calls, it delays the run. Accumulate and process at the end if you don't need real time.
  • An artifacts/ directory that grows unchecked: use rotate_artifacts.
  • AWX API: ignored parameters: if you didn't enable Prompt on launch for that field, AWX ignores it without failing. Check ignored_fields.
  • A token with more permissions than needed: a service user with Execute only on what's essential, like gitea-ci.
  • Tip: keep the artifacts of failed runs; job_events/ contains everything needed to diagnose without running again.

Exercises

Exercise 1: a limit that matches nothing

Modify update.py so that it fails (code 1, with a clear message) if the run finishes without having processed any host, for example with --limit nonexistent.

Exercise 2: check mode

Add a --check option to update.py that runs upgrade.yml in --check mode. Will the tool detect pending reboots in that mode? Reason it out by looking at upgrade.yml.

Exercise 3: canceling an AWX job

Extend awx_launch.py so that, if the user presses Ctrl+C while it's waiting, it cancels the job in AWX before exiting.

Solutions

Exercise 1. After the call to ansible_runner.run, before building the summary:

    if result.status == 'successful' and not stats.get('processed'):
        print('ERROR: the limit "%s" does not match any host.' % args.limit)
        return 1

stats['processed'] contains the hosts that took part; if it's empty, nothing has been done. With a pattern that doesn't match, ansible-playbook only shows a warning ("Could not match supplied host pattern") and finishes successfully.

Exercise 2. A new argument and runner's cmdline parameter:

    parser.add_argument('--check', action='store_true', help='Run in check mode (--check).')
    # ...
    result = ansible_runner.run(
        # ... the same arguments ...
        cmdline='--check' if args.check else None,
    )

Yes, it will detect reboots that are already pending: the stat task on /var/run/reboot-required is read-only and also runs in check mode. What it can't know is whether the upgrade that hasn't been done yet will require a reboot: in check mode, the apt module only computes which packages it would change, without installing them, so the /var/run/reboot-required file doesn't appear. It's a general limitation of check mode: tasks that depend on the effect of an earlier task see the state from before.

Exercise 3. Wrap the waiting loop in try/except KeyboardInterrupt:

    status = None
    try:
        while status not in FINAL:
            time.sleep(5)
            status = api('GET', '/api/v2/jobs/%d/' % job)['status']
            print('  %s' % status)
    except KeyboardInterrupt:
        print('Canceling job %d...' % job)
        api('POST', '/api/v2/jobs/%d/cancel/' % job, {})
        return 1

KeyboardInterrupt is the exception Python raises when you press Ctrl+C. The POST to /cancel/ asks AWX to stop the job, which will move to canceled. Without this, the program would exit but the job would keep running in AWX.

Conclusion

Integrating Ansible into your own programs isn't about importing its internal classes, which have no compatibility guarantees, but about running it through a stable interface. ansible-runner organizes inputs and outputs in a private_data_dir, runs ansible-playbook in a separate process (or in an EE) and delivers every event as structured data, with run(), run_async() and callback functions for reacting in real time; it's the piece AWX, ansible-navigator and EDA use. With it you've written update.py, which upgrades packages and decides which servers need a reboot based on the real result of each task. For what's already an AWX template, the REST API (directly, with awx or with awx.awx) adds centralized credentials, permissions and auditing, as awx_launch.py shows. In both cases, someone or something still has to decide when to launch the automation. In the next lesson, Event-Driven Ansible, you'll take the final step: having Ansible react by itself to what happens in the Aurora Store infrastructure, such as a web server that stops responding or a monitoring alert, and run the appropriate remediation without waiting for anyone to launch it.

Ansible Course: From Beginner to Advanced

Module 1: Introduction to Ansible

Module 2: Ansible Fundamentals

Module 3: Playbooks

Module 4: Roles

Module 5: Advanced Playbook Techniques

Module 6: Ansible Galaxy

Module 7: Ansible Tower, AWX and Automation Platform

Module 8: Ansible for DevOps

Module 9: Ansible Best Practices

Module 10: Advanced Ansible Topics

Module 11: Final Project

© Copyright 2026. All rights reserved