0 / 13 lessons — 0%
Lesson 12 / 13 🔍
Error handling & debugging
By default, if a task fails on one host, Ansible stops running further tasks on that host — but keeps going on every other host in the play. Knowing that default, and how to override it deliberately, avoids a lot of confusion mid-incident.
# ignore a failure on this one task and keep going - name: Attempt to clean old logs (ok if none exist) shell: rm /var/log/app/*.old ignore_errors: true # a command that "fails" normally, but here 1 is actually fine - name: Check for a lockfile command: test -f /tmp/app.lock register: lock_check failed_when: lock_check.rc not in [0, 1] # custom, more readable failure condition - name: Verify service is actually listening shell: curl -sf http://localhost:8080/health register: health failed_when: health.rc != 0
The single most useful debugging tool is register + debug — capture a task's result, then print it to see exactly what Ansible saw.
- name: Get disk usage command: df -h / register: disk_result - name: Show what we got debug: var: disk_result.stdout
# run-time flags that make debugging any playbook easier ansible-playbook site.yml -v # more output ansible-playbook site.yml -vvv # a LOT more output, incl. module internals ansible-playbook site.yml --start-at-task="Deploy config" # resume mid-playbook ansible-playbook site.yml --limit=web3.example.com # retry on just the host that failed
Ansible writes a
.retry file next to your playbook when a run has failures — listing exactly which hosts failed, ready to hand straight to --limit @site.retry so you're not re-running successfully-configured hosts for no reason.Try it yourselfAdd
register + a debug: var: task after any command you're unsure about. Seeing the raw result Ansible captured demystifies conditionals like failed_when almost immediately.