ansible使用 when 进行条件控制
== //等于!= //不等于
1、当 inventory_hostname 等于指定的 机器时,才运行该剧本:
- name: debug: 测试 msg: "测试" when: inventory_hostname == "LEAF-SW-01"
2、使用 or 和 and:
当使用‘when’时,想要两个条件同时满足时,可以使用 and当想要多个条件任意满足一个时,可以使用 or(or 和 and 能够同时使用)
(1)单独使用 or:
- name: debug: 测试 msg: "测试" when: inventory_hostname == "LEAF-SW-01" or 1 != 2
(2)单独使用 and:
- name: debug: 测试 msg: "测试" when: inventory_hostname == "LEAF-SW-01" and 1 == 1
(3)联合使用 and + or:
- name: debug: 测试 msg: "测试" when: inventory_hostname == "LEAF-SW-01" and 1 == 1 or 1 != 1 and 1 == 2
这里可以理解为:" * and * " or "* and *"必须满足 * and *,或者(or) * and *
3、当要定义多条 when 时:
可以使用 - 这种列表的形式
- name: debug: 测试 msg: "测试" when: - inventory_hostname == "LEAF-SW-01" - 1 == 1
不同的 - 之间,相当于 and