Hi,
Ansible does not have a mechanism to keep track of changes and automatically perform a rollback. However, there are a couple of ways you could use to fulfill your requirement:
- Using blocks and rescue: Ansible by default stops playbook execution on a task failure. However, It also provides a mechanism to perform error handling and execute some task in response to a failure. The block section is a logical grouping of all the desired tasks to be executed on a managed host and the rescue section contains the tasks to be executed to recover from the error encountered in block section.
Something like below:
- name: Attempt and graceful roll back demo
block:
- name: i force a failure
command: /bin/false
rescue:
- debug:
msg: 'I caught an error, performing rollback'
command: /bin/false
The only disadvantage of using blocks is that rollback would only be limited to the hosts on which the task has failed in block section. You may refer to the
link for more details.
- Writing an explicit rollback play: If you wish to perform a global rollback, that is on all the hosts, then you need to explicitly write a play with rollback steps and execute it based on some when condition.
Something similar to the below playbook:
---
- hosts: all
gather_facts: false
tasks:
- name: "Deploy"
command: mkdir /tmp/testing/application
register: cmd_result
ignore_errors: true
- debug: msg='Rollback'
- command: rm -rf /tmp/testing/application
when: play_hosts | map('extract', hostvars, 'cmd_result') | selectattr('failed','defined') | list | count > 0