TExcelTAD
Home › Configuration Management: Ansible › Field Notes: Automation You Can Rerun on Friday

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 reports changed hides real changes and fires handlers needlessly: restarts at random times are how "Ansible took prod down" stories start.
  • Every command/shell gets creates, removes or changed_when. Read-only commands get changed_when: false (commands).
  • No state: latest in 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.log
localhost                  : 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.cfg is 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 with serial and max_fail_percentage (rolling updates).
  • any_errors_fatal: true for changes that must not end half-applied (a cluster-wide config change).
  • Use --check --diff as 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 serial and ansible.builtin.reboot (which waits for the host to come back) rather than command: reboot.

Variables you can still reason about

  • One variable, one owner. If a value is set in group_vars/all, a role's vars, and -e in CI, nobody knows which wins (precedence).
  • Prefix by role, keep tunables in defaults/, and validate inputs with argument specs or assert at the top of the role.
  • Pass booleans through | bool: INI inventories and -e key=value give you strings, and since ansible-core 2.19 a string in when: 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: true and diff: false on every task that touches a secret, including debug tasks you added while troubleshooting.
  • The vault password comes from a secret store or CI secret, never from a file in the repository. .gitignore the local .vault_pass.

Speed

  • gather_facts: false where facts aren't used, gather_subset where only some are.
  • pipelining = True and SSH ControlPersist; raise forks for big fleets.
  • Install lists of packages in one module call, not a loop.
  • Profile with the ansible.posix.profile_tasks callback 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 -o and the oneline callback, 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 like apt and package_facts need the distribution's Python bindings (become).

Test yourself

A role's second run reports changed=2. What should you do?

  1. Nothing, that's normal
  2. Find the non-idempotent tasks and fix them (creates/changed_when/state)
  3. Add ignore_errors
  4. Run it a third time

Why validate sshd and sudoers files in the template task?

  1. For speed
  2. A broken file can lock you out of every server it is deployed to
  3. ansible-lint requires it
  4. To encrypt them

Why avoid state: latest in scheduled roles?

  1. It is deprecated
  2. Upgrades then happen at random times during unrelated runs
  3. It doesn't work with apt
  4. It needs Galaxy