How to rollback the ansible-playbook tasks ?

64 views
Skip to first unread message

Stefano Leandro

unread,
Jun 27, 2019, 1:05:24 PM6/27/19
to Ansible Project
Hi Folks,

I would to ask some suggestions for controlling a state rollback of ansible-plyabook tasks .

Are there some best practice to follow ? 


Thank you,

Steano L.

Shivharsh Singh

unread,
Jul 3, 2019, 5:30:58 AM7/3/19
to Ansible Project
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

You may refer to following query for further detail: https://groups.google.com/forum/#!topic/ansible-project/e5a71YmyfqQ 


Thanks,
Shivharsh
Reply all
Reply to author
Forward
0 new messages