To attend this need Ansible provides the attribute block as follows.
tasks:
- block:
# Add here the tasks/actions
rescue:
# Add here the tasks/actions which should be done if the block fails
always:
# Add here what always should be done
Following an example.
tasks:
- block:
- name: Start services
service:
name: "{{ service }}"
enabled: true
state: started
rescue:
- name: Run script if the start services task fail
shell:
cmd: /usr/local/lib/fix-services
always:
- name: Restart the database
service:
name: mongodb
state: restarted
For further information check the Blocks Ansible documentation.