Ansible is a widely used and powerful open-source configuration and deployment management tool. It can be used for simple repetitive daily tasks or complex application deployments, therefore Ansible is able to cover mostly any situation.
Since version 2.0.0 Ansible introduced the usage of blocks, they provide the possibility to group or rescue failed tasks.
On blocks we can assign most directives which are available for any other task at block level, only loops aren’t available.
- name: Update Systems
hosts: all
tasks:
- name: execute this block only for rhel family hosts
block:
- name: install epel repository
yum:
name: epel-release
state: present
- name: install updates
yum:
name: '*'
state: latest
exclude: kernel*
when: ansible_os_family == 'RedHat'
become: true
When we try to deploy applications, sometimes we need to test connections or if requirements are met. When those tasks fail caused by the negative test result, the playbook by default fails and therefore stops.
To force Ansible to execute all other tasks, we could use the directive ignore_failed: true and checking the return value for any other depending task.
With blocks this is easily solved, by using rescue to catch the error and force a particular tasks to run.
The always will make sure that the listed tasks get executed.
- name: rescue my errors
hosts: localhost
tasks:
- name: Try to reach host
block:
- name: "[Try reach DNS] Check Connection over DNS"
command: ping client01.demo.local -c 2
register: output
rescue:
- name: "[Rescue failed DNS] Check Connection over IP"
command: ping 192.168.33.1 -c 2
register: output
always:
- debug:
var: output
To handle more than one rescue statement, the block can be simply used in the rescue section, like in the following example.
- name: Try to execute skript
block:
- name: Check Connection over DNS
command: ping nclient01.demo.local -c 2
register: output
rescue:
- name: "this will fail"
block:
- name: it will be false
command: /bin/false
register: output
rescue:
- name: "this works"
command: ping 192.168.33.1 -c 2
register: output
Try to reduce ignored tasks in failed state with rescue blocks, this reduces the confusion of users when inspecting the output.
As second advice try to reduce code duplication by grouping tasks with similar directives.
Check out our Blog for more awesome posts and if you need help with Ansible send us a message or sign up for one of our trainings!
