转载说明:如果您喜欢这篇文章并打算转载它,请私信作者取得授权。感谢您喜爱本文,请文明转载,谢谢。
shell、Python等都有逻辑控制,Ansible也不例外,也有自己的逻辑控制语句,如:
when:条件判断语句,类似于shell中的if;
loop:循环语句,类似于 shell中的while;
block:把几个任务组成一个代码块,以便于针对一组操作的异常进行处理等操作。
when判断
1. 基于facts变量的条件
1.1 基于单个条件判断
例如,在下面的例子中,如果test组里面有指定的IP,就将信息打印出来:
[root@test101 ansible-test]# cat when-test1.yaml
---
- hosts: testremote_user: root#gather_facts: notasks:- name: test of whendebug:msg: "Host 10.0.0.102 is in the test group"when: ansible_default_ipv4.address == "10.0.0.102"
[root@test101 ansible-test]#
执行结果:
1.2 基于多个条件判断
例如下面的例子,如果远端主机是x86_64,且IP是指定IP,则执行reboot。满足的两个条件可以按照写法一种用and连接,也可以按照写法二中用将条件罗列出来。
[root@test101 ansible-test]# cat when-test2.yaml
---
- hosts: testremote_user: root#gather_facts: notasks:- name: Restart my servercommand: /usr/sbin/reboot## 写法一:##when: ansible_default_ipv4.address == "10.0.0.103" and ansible_architecture == "x86_64"## 写法2when:- ansible_architecture == "x86_64"- ansible_default_ipv4.address == "10.0.0.103"
[root@test101 ansible-test]#
执行结果:
如果满足的多个条件之间的关系不是and,而是“或者”的关系,则可以这样写:
[root@test101 ansible-test]# cat when-test3.yaml
---
- hosts: testremote_user: root#gather_facts: notasks:- name: Restart my servercommand: /usr/sbin/reboot## 写法一:# when: ansible_default_ipv4.address == "10.0.0.103" or ansible_architecture == "x86_64"## 写法二:when: >ansible_architecture == "x86_64"oransible_default_ipv4.address == "10.0.0.103"
[root@test101 ansible-test]#
执行结果:
如果条件中既包含and关系,也包含or的关系,则可以这样写:
[root@test101 ansible-test]# cat when-test4.yaml
---
- hosts: testremote_user: root#gather_facts: notasks:- name: Restart my servercommand: /usr/sbin/reboot## 写法一:#when: (ansible_default_ipv4.address == "10.0.0.102" and ansible_architecture == "x86_64") or (ansible_default_ipv4.address == "10.0.0.103" and ansible_architecture == "x86_64")## 写法二:when: >(ansible_default_ipv4.address == "10.0.0.102" and ansible_architecture == "x86_64")or(ansible_default_ipv4.address == "10.0.0.103" and ansible_architecture == "x86_64")
[root@test101 ansible-test]#
2. 基于Action执行结果的条件
例如,判断远程主机是否存在/tmp/test.txt这个文件,如果存在,则打出存在该文件的主机IP:
[root@test101 ansible-test]# cat when-test5.yaml
---
- name: test of whenhosts: testtasks:- name: Check if a file existsstat:path: /tmp/test.txtregister: file_check_result- name: Perform action based on file existencedebug:msg: "File exists on {{ ansible_host }}"when: file_check_result.stat.exists
[root@test101 ansible-test]#
执行结果:
3. 其它使用场景
when还可以与with_items共用,用于简单的数字判断:
[root@test101 ansible-test]# cat when-test6.yaml
---
- hosts: testgather_facts: notasks:- name: test of when#command: echo {{ item }}debug:msg: item is {{ item }}with_items: [ 0, 3, 5, 8, 10, 26 ]when: item > 6
[root@test101 ansible-test]#
执行结果:
未完待续......