failed_when 和 changed_when

failed_when关键字的作用是在条件成立时,将对应任务的执行状态设置为Failed

  • 任务的执行结果控制:
    • 在 Ansible 1.4 之前,fail模块
    • 在 Ansible 1.4 之后,failed_when

changed_when关键字的作用是在条件成立时,将对应任务的执行状态设置为changed

failed_when

在任务执行失败时,ansible-playbook会返回这个task failed,但是有些时候,我们希望playbook按照我们的意愿中断任务,以返回值中的特定字符串 做为 中断这个task的条件,当条件成立时将对应任务的状态设置为失败,中止剧本。

failed_when 示例:

1
2
3
4
5
6
7
8
9
10
11
12
---
- hosts: web1
#gather_facts: no
remote_user: root
tasks:
- debug:
msg: "I execute normally, Before the condition judgment starts"
- shell: "echo 'This is a string for testing error'"
register: return_value
failed_when: ' "error" in return_value.stdout'
- debug:
msg: "I execute normally, Because the condition doesn't hold"

changed_when

在使用command /shell 模块的时候ansible playbook 会按照自己的判断来决定是否changed了,有时候我们仅仅是ls 了一下,ansible-playbook 也会认为是changed了,可能这并不是我们想要的,这个时候我们就要用例子中方法来修改task的状态了

当changed_when状态被设置为false时,不管原任务状态为啥,最终都会被设置为ok状态

1
2
3
4
5
6
---
- hosts: all
remote_user: root
tasks:
- shell: "ls /opt"
changed_when: False

在条件成立时,将任务状态改为changed

1
2
3
4
5
6
7
---
- hosts: all
remote_user: root
tasks:
- debug:
msg: "test message"
changed_when: 2 > 1

参考文档