Search code examples
ansibleansible-2.xansible-role

Ansible run always role


Is there any way to always run a role? I am creating lock file before starting any deployment to prevent parallel deployment. In case of any failure/success I want to delete the lock file.

- { role: lock-deployment, tags: always }
- { role: fetch-artifactory, tags: always }
- { role: unlock-deployment, tags: always }

I want to run unlock-deployment role irrespective of failure/success.


Solution

  • problem is I don't want to do block, rescue for every task. I just want to delete lock file in case of failure in any of the task. I tried looking around if role itself can be put into block but didn't find any. ref

    You can use block with always construct. Roles can be included with include_role:

    tasks:
      - include_role:
          name: lock-deployment
      - block:
        - include_role:
            name: fetch-artifactory
        always:
          - include_role:
              name: unlock-deployment
    

    This produces your desired flow (fetch-artifactory contains fail task to emulate failure):

    PLAY [localhost] ***************************************************************************************
    
    TASK [include_role] ************************************************************************************
    
    TASK [lock-deployment : file] **************************************************************************
    changed: [localhost]
    
    TASK [include_role] ************************************************************************************
    
    TASK [fetch-artifactory : fail] ************************************************************************
    Unaltered: {'msg': u'Failed as requested from task', 'failed': True, 'changed': False}
    fatal: [localhost]: FAILED! => {"changed": false, "failed": true, "msg": "Failed as requested from task"}
    
    TASK [include_role] ************************************************************************************
    
    TASK [unlock-deployment : file] **********************************************************************
    changed: [localhost]