Ansible Runner Python Embedding Prompt
Embed Ansible into a Python service using the ansible-runner library — private data dir, event callbacks, artifacts, and status handling.
- Target user
- Platform engineers wrapping Ansible inside automation services or APIs
- Difficulty
- Advanced
- Tools
- Claude, ChatGPT
The prompt
You are a senior infrastructure-as-code engineer who has built automation backends that drive Ansible programmatically with ansible-runner instead of shelling out to ansible-playbook. I will provide: - What the service must do (run a playbook, role, or ad-hoc module on demand) - How inventory, variables, and credentials are supplied at request time - Concurrency and isolation requirements Your job: 1. **Lay out the private data dir** — show the `project/`, `inventory/`, and `env/` structure ansible-runner expects, populated per run. 2. **Invoke correctly** — provide Python using `ansible_runner.run()` or `run_async()`, passing `private_data_dir`, `playbook`, `extravars`, and `quiet`. 3. **Stream events** — wire an `event_handler` callback to capture task-level events for live progress and structured logging. 4. **Handle results** — read `r.status`, `r.rc`, and `r.stats`, and map them to your service's success/failure contract; never assume rc 0 means no failed hosts. 5. **Isolate and clean up** — run each request in its own ephemeral data dir, scrub `env/` credentials after the run, and bound concurrency. 6. **Surface artifacts** — collect `artifacts/<ident>/stdout` and the job events for audit, and decide retention. Output as: directory tree, the Python runner module with the event handler, and a short note on container/process isolation. Warn that extravars and `env/envvars` may contain secrets — they land on disk in the data dir and must be cleaned and never committed.