1、数据收集:register
用于捕获命令的输出,将结果作为变量,方便结果在下面的调试,调用。
## 将结果直接获取
1 ---
2 - name:
3 tasks:
4 - name: run script
5 shell: /usr/local/bin/user.sh
6 register: command_result ##命令结果存入command_result
7 - name: debug
8 debug:
9 msg: command_result.stdout ##查看命令中的标准输出
2、触发条件:when
只有当when的条件为真时,被when标记的任务才可执行
##when条件为真时,才可执行
1 ---
2 - name: Boolean test
3 hosts: all
4 vars:
5 run_my_task: true
6 tasks:
7 - name: httpd is installed
8 yum:
9 name: httpd
10 when: run_my_task
when的判定可以和变量的判定进行组合,只需要条件为真即可,例如:when xxx is defined (当xxx变量存在时,执行)
3、变量的判定:
判断方式 | 含义结果 |
== | 等于 |
< | 小于 |
> | 大于 |
<= | 小于等于 |
>= | 大于等于 |
!= | 不等于 |
xxx is defined | 变量存在 |
xxx is not defined | 变量不存在 |
true 1 yes | 布尔值 真 |
false 0 no | 布尔值 假 |
or | 逻辑或 |
and | 逻辑于 |
A in B | A存在且在B中 |
这里条件的使用和c语言里面的基本一致,不做过多赘述。
结合when的实例
##结合when做判定
1 ---
2 - name: Boolean test
3 hosts: all
4 vars:
5 run_my_task: httpd
6 tasks:
7 - name: httpd is installed
8 yum:
9 name: httpd
10 when: ##当系统为RedHat且版本为8 或者 系统为CentOS 且版本为7时执行
11 ( ansible_distribution == "RedHat" and
12 ansible_distribution_major_version == "8" ) or
13 ( ansibel_distribution == "CentOS" and
14 ansible_distribution_,ajor_version == "7")
4、忽略报错:ignore_errors
忽略失败的任务继续执行下面的任务
## K8s不存在yum仓库,安装时会报错
1 ---
2 - name: ignore_errros
3 hosts: all
4 tasks:
5 - name: install package
6 yum:
7 name: k8s
8 state: latest
9 ignore_errors: yes
执行结果:
5、强制执行处理程序:force_handlers
通常任务失败,play中止则play中收到的之前任务通知的处理程序将不会运行,为了使之前的通知可以运行
## 强制执行触发器
1 ---
2 - name: force
3 hosts: all
4 force_handlers: yes
5 tasks:
6 - name: always notify
7 command: /bin/true
8 notify: restart apache
9
10 - name: fail task ##该任务会失败,yum中不存在k8s的包
11 yum:
12 name: k8s
13 state: latest
14
15 handlers:
16 - name: restart apache
17 service:
18 name: httpd
19 state: restarted
结果分析:
6、指定任务失败条件:failed_when
在一些特殊情况下,需要指定该任务失败,但要求该任务执行(block块中会出现要求block和rescue均执行)
##指定任务失败
tasks:
- name: run script
shell: /usr/local/bin/user.sh
register: command_result
failed_when: "'failure' is command_result.stdout" ##当输出结果有failure时,任务失败
7、指定changed结果:changed_when
当处理器需要执行时,changed必须有结果,我们可以通过测试触发器,进行测试。
#设定changed_when为false不改变
1 ---
2 - name: get time
3 hosts: all
4 tasks:
5 - name: get time
6 shell: date
7 changed_when: false
8 notify: check time
9
10 handlers:
11 - name: check time
12 shell: date
13
测试结果:
注释掉changed_when,再测试