根据角色执行状态执行 Ansible 任务



我有一个角色pkg_install,有什么方法可以根据角色执行的状态执行post_tasks吗? 如果角色pkg_install失败,还要忽略错误?

- name: status file
hosts: localhost
gather_facts: false
roles:
- role: "pkg_install"
register: status
ignore_errors: true
post_tasks
- name: status DEBUG
debug:
msg: "pkg_install success"
when: status is successful

请注意,在代码中使用类似ignore_errors就像在角色中的每个任务上放置ignore_errors,因此如果角色中的任何任务失败,它将继续执行角色中的下一个任务并执行post_tasks。

如果您希望角色在失败时停止,但重头戏的其余部分继续并知道角色是否失败,则可以执行以下操作:

- name: status file
hosts: localhost
gather_facts: false
tasks:
- block:
- import_role: 
name: "pkg_install"
rescue:
- set_fact:
role_success: no
post_tasks:
- name: status DEBUG
debug:
msg: "pkg_install success"
when: role_success|default('yes')|bool

仅当角色失败时,救援任务才会运行。 这是关于块的文档以获取更多信息 https://docs.ansible.com/ansible/latest/user_guide/playbooks_blocks.html

最新更新