Ansible: Error Handling

Ansible stops executing on the host whenever it receives a non-zero return code from a command. We can handle these situations with the helps of settings and tools to behave as it we want.

Ignoring Errors Ansible stops executing commands on the host when it receives non-zero code, but we can ignore these errors and run the rest of the tasks as it is.

- name: I will cause an error
  ignore_errors: yes

Failed when Ansible let you define the condition when you want explicitly fail when a certain condition is true.

- name: Fail task under certain condition true
  command: ls/tmp/dir_not_exist
  register: result
  failed_when: result.rc == 0

Aborting on first error anyerrorsfatal finishes the fatal task on all hosts in the current batch, then stops executing on all hosts.

- hosts: somehosts
  any_errors_fatal: true
    - block:
         - include_tasks: sometask.yml

Handling errors with blocks Ansible let you control errors in a block with rescue and always section. In rescue, we can define tasks which we want to run when an earlier task in a block fails. You can also think of rescue as except and always as finally in other languages to handle errors.

- name: tasks to be run
     - name: task 1
       // code
     - name: task 2
       // code
     - name: task 3
       // code
     - name: Run when one of the above task fails
       // code
     - name: Always run 
       // code

Ansible provide ignore, rescue, always, failed_when to easily handle the behavior of playbook when we face any errors. We can use these commands/settings to gracefully record errors and take specific action.


#100DaysToOffload #Ansible