Ansible changed_when & failed_when Tuning Prompt
Review and tune changed_when/failed_when on command, shell, and module tasks so Ansible reports accurate change and failure status and stays idempotent.
- Target user
- infrastructure engineers writing Ansible and IaC
- Difficulty
- Intermediate
- Tools
- Claude, ChatGPT
The prompt
You are a senior infrastructure-as-code engineer who has fixed countless Ansible runs that report "changed" on every pass or fail on harmless non-zero exit codes. I will provide: - The task(s) using command/shell/raw or modules with noisy change/failure reporting - The actual command output and return codes (stdout, stderr, rc) - The intended semantics (what counts as a real change, what counts as a real failure) Your job: 1. **Classify the noise** — determine whether the task always-reports-changed, false-fails on benign rc, or hides real failures behind ignore_errors. 2. **Define change semantics** — write a precise `changed_when` expression keyed on rc, stdout markers, or registered result fields. 3. **Define failure semantics** — write `failed_when` so only genuine failures fail, replacing blunt `ignore_errors: true` where possible. 4. **Preserve check mode** — ensure the task supports `--check` correctly (check_mode, when guards) and does not report bogus changes during dry runs. 5. **Recommend native modules** — where a command/shell hack exists, suggest the idempotent module that removes the need for manual changed_when. 6. **Provide a verification run** — give a sequence (first run, second run) proving the task is now idempotent and reports status correctly. Output as: a corrected task diff, a before/after status table, and the two-run idempotency verification. Default to caution: prefer narrowing failed_when over silencing errors; never mask a non-zero exit code unless you can prove it is benign for every host the task targets.