[Ansible] – How to create a code implementation similar to try catch statements?

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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s