Ansible 运行 总是角色

Ansible run always role

有什么办法可以一直运行一个角色吗?我在开始之前创建锁定文件 任何部署以防止并行部署。如果有 failure/success 我 想删除锁定文件。

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

我想 运行 解锁部署角色,而不考虑 failure/success。

对于这种情况,您可以使用 Ansible blockalways

http://docs.ansible.com/ansible/latest/playbooks_blocks.html

如何使用 block 并包含来自角色的 yaml 文件而不是将角色声明为依赖项:

tasks:
  - name: "start deployment"
    block:
      - include: "<path to roles>/lock-deployment/tasks/main.yaml"
      - include: "<path to roles>/fetch-artifactory/tasks/main.yaml"
      - include: "<path to roles>/unlock-deployment/tasks/main.yaml"
    always:
      - name: "remove lock file"
        ...

如果您需要包含 roles 中的 default 个变量,您可以这样做:

roles:
  - { role: lock-deployment,
      when: False
    }

我的解决方案不是一个优雅的解决方案,但我真的建议从 roles 开始执行这些操作,而改为执行 includes

另外:我没有测试过这个解决方案,可能无法实际工作。但它提供了替代解决方案的想法。

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.

可以blockalways结构结合使用。角色可以包含在 include_role:

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

这会产生您想要的流程(fetch-artifactory 包含 fail 模拟失败的任务):

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]