TExcelTAD
Home › Configuration Management: Ansible › Blocks & Error Handling

Blocks & Error Handling

A block groups tasks so they can share keywords (when, become, tags, vars) and, more importantly, handle errors together, like try / except / finally:

Section Runs
block: the tasks
rescue: only if a task in block failed; the failure is then considered handled
always: afterwards, whether the block failed or not

A deployment with a rollback

The pattern below switches a current symlink to a new release, runs a health check, and rolls back if it fails:

bash · try it yourself
mkdir -p app/releases/v1 app/releases/v2 && cd app
echo ok > releases/v1/health
echo broken > releases/v2/health
ln -s /home/learner/app/releases/v1 current
cat > deploy.yml <<'YML'
- name: Deploy with rollback
  hosts: localhost
  gather_facts: false
  vars:
    app_root: /home/learner/app
    new_release: v2
  tasks:
    - name: Remember the current release
      ansible.builtin.stat:
        path: "{{ app_root }}/current"
      register: before

    - name: Switch and verify
      block:
        - name: Point current at the new release
          ansible.builtin.file:
            src: "{{ app_root }}/releases/{{ new_release }}"
            dest: "{{ app_root }}/current"
            state: link

        - name: Health check
          ansible.builtin.command: cat {{ app_root }}/current/health
          register: health
          changed_when: false
          failed_when: health.stdout != "ok"

      rescue:
        - name: Roll back
          ansible.builtin.file:
            src: "{{ before.stat.lnk_source }}"
            dest: "{{ app_root }}/current"
            state: link

        - name: Fail the run after rolling back
          ansible.builtin.fail:
            msg: "release {{ new_release }} failed its health check, rolled back"

      always:
        - name: Record the attempt
          ansible.builtin.lineinfile:
            path: "{{ app_root }}/deploy.log"
            line: "tried {{ new_release }}"
            create: true
            mode: "0644"
YML
# the sed removes the command's start/end/delta timestamps, which change on every run
ansible-playbook deploy.yml | grep -E '^(TASK|ok|changed|fatal|failed)|PLAY RECAP|^localhost' \
  | sed -E 's/"(start|end|delta)": "[^"]*", //g'
readlink current; cat deploy.log
TASK [Remember the current release] ********************************************
ok: [localhost]
TASK [Point current at the new release] ****************************************
changed: [localhost]
TASK [Health check] ************************************************************
fatal: [localhost]: FAILED! => {"changed": false, "changed_when_result": false, "cmd": ["cat", "/home/learner/app/current/health"], "failed_when_result": true, "msg": "Task failed: Action failed: A 'failed_when' expression evaluated to 'True'.", "rc": 0, "stderr": "", "stderr_lines": [], "stdout": "broken", "stdout_lines": ["broken"]}
TASK [Roll back] ***************************************************************
changed: [localhost]
TASK [Fail the run after rolling back] *****************************************
fatal: [localhost]: FAILED! => {"changed": false, "msg": "release v2 failed its health check, rolled back"}
TASK [Record the attempt] ******************************************************
changed: [localhost]
PLAY RECAP *********************************************************************
localhost                  : ok=4    changed=3    unreachable=0    failed=1    skipped=0    rescued=1    ignored=0
/home/learner/app/releases/v1
tried v2

Read the recap: the failed health check counts as rescued=1, the fail task we put in rescue makes the run fail on purpose (failed=1), and always still wrote the log. Without that final fail, the run would end green, and nobody would notice the rollback. Decide deliberately whether a rescued failure should fail the pipeline.

Inside rescue, ansible_failed_task and ansible_failed_result describe what failed, for messages and notifications.

Other error controls

Keyword Effect
ignore_errors: true a failure is printed but the play continues (ignored=1 in the recap); use sparingly
failed_when: your own definition of failure (commands)
ignore_unreachable: true keep going when a host can't be reached
any_errors_fatal: true (play) one failure on any host stops the play on all hosts: for changes that must not end half-applied
max_fail_percentage: 20 (play) stop when more than 20% of the hosts failed, together with serial

ignore_errors hides problems; a block/rescue that does something about the failure is almost always better.

Shared keywords on a block

yaml
- name: Everything that needs root and only runs on Debian
  become: true
  when: ansible_facts['os_family'] == "Debian"
  tags: [packages]
  block:
    - name: Install packages
      ansible.builtin.apt:
        name: [nginx, fail2ban]
    - name: Enable fail2ban
      ansible.builtin.service:
        name: fail2ban
        state: started
        enabled: true

Test yourself

A task in block fails and rescue runs successfully. How does the PLAY RECAP count it?

  1. failed=1
  2. rescued=1, and the host is not failed
  3. ignored=1
  4. skipped=1

When does always: run?

  1. Only on success
  2. Only on failure
  3. In both cases
  4. Only with --check

Which play keyword stops the play on every host as soon as one host fails?

  1. ignore_errors
  2. any_errors_fatal: true
  3. serial: 1
  4. force_handlers