Ansible and Exception Handling

From bib. source

[…], Blocks allow you to group related tasks together and apply particular task parameters on the block level. They also allow you to handle errors inside the blocks in a way similar to most programming languages’ exception handling.

A block, for Ansible, involves a block field that, under it, holds tasks for which certain parameters hold (Geerling 2023, 119-120). Other fields may be specified for those tasks under the block field, at the same level as the block field, which affect those tasks collectively. E.g. (Geerling 2023, 120),

---
- hosts: web
  tasks:
    # Install and configure Apache on RHEL/CentOS hosts
    - block:
        - dnf: name=httpd state=present
        - template: src=httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf
        - service: name=httpd state=started enabled=yes
      when: ansible_os_family == 'RedHat'
      become: yes

Note

For background on when and become in particular, look into conditionals in Ansible as well as running Ansible playbooks.

Blocks also allow the graceful handling of exceptions or errors, i.e. allow for error handling or exception handling, if the block field is juxtaposed with the rescue and then always fields (on the same level) (Geerling 2023, 121). Any “failure in any task in block¨ will lead to “tasks inside rescue¨ to be run (Ibid). Meanwhile, tasks inside the always field will always be run regardless of failures within either the block or rescue fields (Ibid). Example (Ibid):

tasks:
  - block:
      - name: Script to connect the app to a monitoring service.
        script: monitoring-connect.sh
    rescue:
      - name: This will only run in case of an error in the block.
        debug: msg="There was an error in the block."
    always:
      - name: This will always run, no matter what.
        debug: msg="This always executes."

Alternatively, error or exception handling can be done by using failed_when instead (refer to [[20250517180510-Conditionals_in_Ansible#the-changed_when—failed_when-fields|The changed_when / failed_when fields]]) (Ibid).

error_handling exception_handling error programming_language programming_languages


bibliography

  • “Ansible Playbooks - Beyond the Basics.” In Ansible for DevOps: Server and Configuration Management for Humans, 2nd ed., 84–122. Leanpub, 2023.