绝大多数语言中,都使用"if"作为条件判断的关键字,而在ansible中,条件判断的关键字是"when"
我们可以使用when关键字为任务指定条件,条件成立,则执行任务,条件不成立,则不执行任务,
一、条件判断方式
二、具体使用
1.布尔值与when
2.是否存在或定义
3.loop循环与when
register与when
当我们调用shell模块运行命令时,通常需要获取到shell模块的返回信息,以便之后的模块能够根据返回信息的值判断之后进行怎样的操作,示例如下,如下示例存在一个问题,我们一起来看一下
[root@server4 ~]# vim pd4.yml
[root@server4 ~]# cat pd4.yml
---
- hosts: testB
remote_user: root
tasks:
- name: task1
shell: "ls /testabc"
register: returnmsg
ignore_errors: true
- name: task2
debug:
msg: "Command execution successful"
when: returnmsg.rc == 0
- name: task3
debug:
msg: "Command execution failed"
when: returnmsg.rc != 0
通过"ignore_errors"关键字即可实现这种效果,"ignore_errors"表示即使当前task执行报错,ansible也会忽略这个错误,继续执行playbook
root@server4 ~]# vim pd2.yml
[root@server4 ~]# cat pd2.yml
---
- hosts: testB
remote_user: root
gather_facts: no
tasks:
- debug:
msg: "{{item}}"
with_items:
- 1
- 2
- 3
when: item > 1
上例表示当item的值大于1时,才会调用debug模块输出对应的信息:
4.fact事实变量与when
[root@server4 ~]# vim pd1.yml
[root@server4 ~]# cat pd1.yml
---
- hosts: testB
remote_user: root
tasks:
- debug:
msg: "System release is RedHat"
when: ansible_distribution == "RedHat"
如上例所示,使用when关键字指明条件,条件是ansible_distribution的值是RedHat,我们可以发现,ansible_distribution就是facts信息中的一个key,通过ansible_distribution可以获取到目标主机系统的发行版,在之前的文章中,如果我们需要获取到facts中的key的值,都是通过引用变量的方式获取的,即"{{ key }}",但是,在使用when关键字时,我们并没有为ansible_distribution添加"{{ }}",没错,在when关键字中引用变量时,变量名不需要加"{{ }}", 那么上例playbook表示,如果ansible_distribution的值是RedHat,则调用debug模块,输出"System release is RedHat"这句话,如果ansible_distribution的值不是RedHat,则不满足条件,则不会调用debug模块,我们可以使用when关键字为任务指定条件,条件成立,则执行任务,条件不成立,则不执行任务,
三、逻辑运算符
[root@server4 ~]# vim pd3.yml
[root@server4 ~]# cat pd3.yml
---
- hosts: testB
remote_user: root
tasks:
- debug:
msg: "System release is RedHat7"
when: ansible_distribution == "RedHat" and ansible_distribution_major_version == "7"
上例表示,如果想要debug模块能够输出"System release is RedHat7"这句话,需要同时满足两个条件,ansible_distribution的值是RedHat,同时ansible_distribution_major_version的值是7
再来看一个示例,这个示例同时用到了逻辑与、逻辑或、分组组合,
[root@server4 ~]# vim pd3.yml
[root@server4 ~]# cat pd3.yml
---
- hosts: testB
remote_user: root
tasks:
- debug:
msg: "System release is RedHat7 or RedHat6"
when: ansible_distribution == "RedHat" and ( ansible_distribution_major_version == "7" or ansible_distribution_major_version == "6")
还有"取反"的示例,如下示例表示如果系统的发行版不是centos,则输出"System release is not centos"这句话
[root@server4 ~]# vim pd3.yml
[root@server4 ~]# cat pd3.yml
---
- hosts: testB
remote_user: root
tasks:
- debug:
msg: "System release is not Centos"
when: not ansible_distribution == "Centos"