Field Notes: Automation You Can Rerun on Friday
Lessons from Ansible code that went wrong in production, grouped by the mistake they prevent. The goal: a playbook you would rerun on any server, any day, without fear.
A rerun must be boring
- The second run must say
changed=0. Test it with Molecule's idempotence stage on every role. A task that always reportschangedhides real changes and fires handlers needlessly: restarts at random times are how "Ansible took prod down" stories start. - Every
command/shellgetscreates,removesorchanged_when. Read-only commands getchanged_when: false(commands). - No
state: latestin roles that run on a schedule: one day a new upstream version arrives in the middle of a run that was only meant to fix a config line. Upgrade packages in a dedicated, deliberate play. - Templates must not contain timestamps or random values (
{{ ansible_date_time }},{{ 1000 | random }}without a seed): every run would change the file.
The quickest local check is two runs in a row:
bash · try it yourself
cat > role-check.yml <<'YML'
- name: Idempotency smoke test
hosts: localhost
gather_facts: false
tasks:
- name: Good, a desired state
ansible.builtin.lineinfile:
path: app.env
line: LOG_LEVEL=info
create: true
mode: "0644"
- name: Bad, appends on every run
ansible.builtin.shell: echo "started" >> app.log
YML
for run in 1 2; do ansible-playbook role-check.yml | grep '^localhost'; done
ansible-playbook role-check.yml | grep -B1 '^changed' | grep TASK
wc -l < app.loglocalhost : ok=2 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
localhost : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
TASK [Bad, appends on every run] ***********************************************
3
The TASK line printed on the third run names the culprit, and app.log has grown with every run.
Blast radius
- Production must be opt-in: the default inventory in
ansible.cfgis staging; production needs-i inventories/prod. Better: separate CI jobs with separate credentials. - Canary first:
--limit web1 --check --diff, then--limit web1, then the rest withserialandmax_fail_percentage(rolling updates). any_errors_fatal: truefor changes that must not end half-applied (a cluster-wide config change).- Use
--check --diffas the "plan" in review: paste its output into the merge request.
Never lock yourself out
- SSH, sudoers and firewall changes are the classic ways to lose access to 200 servers at once. Always
validate:(sshd -t -f %s,visudo -cf %s), and keep the current session open while testing (linux-admin). - Apply firewall rules with an allow rule for your management network before a default-deny policy, in the same task file, and test on one host first.
- When a play reboots hosts, use
serialandansible.builtin.reboot(which waits for the host to come back) rather thancommand: reboot.
Variables you can still reason about
- One variable, one owner. If a value is set in
group_vars/all, a role'svars, and-ein CI, nobody knows which wins (precedence). - Prefix by role, keep tunables in
defaults/, and validate inputs with argument specs orassertat the top of the role. - Pass booleans through
| bool: INI inventories and-e key=valuegive you strings, and since ansible-core 2.19 a string inwhen:is an error rather than a silent "true". - Watch for reserved names (
port,environment,name): ansible-core 2.21 warns about them; treat the warning as an error.
Secrets
- Vault-encrypt every secret file;
vault_prefix and a plain alias for readability (Vault). no_log: trueanddiff: falseon every task that touches a secret, includingdebugtasks you added while troubleshooting.- The vault password comes from a secret store or CI secret, never from a file in the repository.
.gitignorethe local.vault_pass.
Speed
gather_facts: falsewhere facts aren't used,gather_subsetwhere only some are.pipelining = Trueand SSHControlPersist; raiseforksfor big fleets.- Install lists of packages in one module call, not a loop.
- Profile with the
ansible.posix.profile_taskscallback before optimising anything else.
Keep the toolchain pinned
- Pin
ansible-core,ansible-lint, Molecule and every collection (requirements.yml). Each new ansible-core release deprecates something (2.21 deprecates-oand theonelinecallback, as the lab showed); upgrade on purpose, read the porting guide, fix the warnings. - Run the modules with the host's system Python (
/usr/bin/python3) unless you have a reason not to: modules likeaptandpackage_factsneed the distribution's Python bindings (become).
Test yourself
A role's second run reports changed=2. What should you do?
- Nothing, that's normal
- Find the non-idempotent tasks and fix them (creates/changed_when/state)
- Add
ignore_errors - Run it a third time
Why validate sshd and sudoers files in the template task?
- For speed
- A broken file can lock you out of every server it is deployed to
- ansible-lint requires it
- To encrypt them
Why avoid state: latest in scheduled roles?
- It is deprecated
- Upgrades then happen at random times during unrelated runs
- It doesn't work with apt
- It needs Galaxy