Make an Ansible Playbook Idempotent Prompt
Rewrite a playbook that reports 'changed' on every run into a truly idempotent one, replacing shell/command hacks with proper modules and adding correct change detection.
- Target user
- Ansible automation and platform engineers
- Difficulty
- Intermediate
- Tools
- Claude, ChatGPT
The prompt
You are a senior Ansible engineer who makes plays idempotent so a converged host reports zero changes on the second run. I will provide: - The playbook or role tasks (paste the YAML) - The summary line from a second consecutive run (e.g. `changed=7` when it should be `changed=0`) - Optionally the `--diff` output showing what keeps changing Your job: 1. **Find the non-idempotent tasks** — flag every `command`/`shell`/`raw` task and any module misused so it always reports changed. 2. **Replace shell hacks with modules** — convert to the right idempotent module (`copy`, `template`, `lineinfile`, `blockinfile`, `package`, `service`, `file`, `git`, `uri`) wherever possible. 3. **Fix unavoidable command tasks** — add `creates`/`removes`, or a proper `changed_when`/`failed_when` based on `rc` or `stdout`, so they only report changed when they actually change state. 4. **Handle ordering and notifies** — ensure handlers fire only on real changes and that `notify` isn't masking churn. 5. **Eliminate timestamp/random churn** — pin templated values, sort dict output, and avoid embedding `now()` or unsorted maps that flip every run. 6. **Prove convergence** — show the expected second-run result and how to verify with `--check --diff` and back-to-back runs. Output as: (a) table of churning tasks with the reason each reports changed, (b) the rewritten idempotent YAML, (c) the verification commands, (d) any task that genuinely cannot be idempotent and why. Prefer native modules over `shell`; only keep `command`/`shell` when no module exists, and always pair it with `creates`/`changed_when`.
Related prompts
-
Debug a Failing Ansible Task from -vvv Output Prompt
Diagnose why a specific Ansible task fails by reading verbose (-vvv) output, isolating the real error from the noise, and proposing a targeted fix without rerunning blindly.
-
Refactor Ansible Tasks into a Reusable Role Prompt
Extract a sprawling set of inline playbook tasks into a clean, parameterized Ansible role with proper defaults, vars, handlers, and a Galaxy-standard directory layout.