1.忽略任务失败
Ansible 默认会检查命令和模块的返回状态,并进行相应的错误处理,默认是遇到错误就中断 playbook 的执行,这些默认行为都是可以改变的,可以通过 ignore_errors 忽略返回状态码
---
- name: test
hosts: rhel8_no1.test.com
tasks:
- name: install packages
yum:
name: haha ##不存在的安装包
state: latest
ignore_errors: yes ##忽略错误
2.任务失败后强制执行处理程序
通常任务失败,playbook 会终止,那么收到 play 中之前任务通知的处理程序将不会运行,如果要运行,需要使用关键字:force_handlers:yes
---
- hosts: rhel8_no1.test.com
force_handlers: yes ##强制执行处理任务
tasks:
- name: always notify
command: /bin/true
notify: restart apache
- name: Fail task
yum:
name: haha ##错误任务
state: latest
handlers:
- name: restart apache
service:
name: httpd
state: restarted
3.指定任务失败条件
关键字:failed_when
- hosts: rhel8_no1.test.com
tasks:
- name: Run Script
shell: /usr/local/bin/user.sh
register: command_result
failed_when: "'failure' in command_result.stdout" ##如果命令输出结果中有failure字符串,则任务失败
fail 模块也可以实现此效果
- hosts: rhel8_no1.test.com
tasks:
- name: Run Script
shell: /usr/local/bin/user.sh
register: command_result
ignore_error: yes
- name: Report failure
fail:
msg: "Authentication failure" ##fail 模块可以提供明确消息
when: "'failure' in command_result.stdo"
4.指定任务何时报告"Changed"结果
关键字:changed_when
- hosts: rhel8_no1.test.com
tasks:
- name: get time
shell: date
changed_when: false ##不报告changed结果
5.ansible 块和错误处理
三种关键字:
- block:定义要运行的主要任务
- rescue:定义要在 block 子句中定义的任务失败时运行的任务
- always:定义始终独立运行的任务
---
- name: Task Failure
hosts: rhel8_no1.test.com
vars:
web_pkg: http ##错误安装包
db_pkg: mariadb-server
db_service: mariadb
tasks:
- name: Set up web
block:
- name: install {{web_pkg}} packages
yum:
name: "{{web_pkg}}" ##任务执行失败
state: present
rescue:
- name: install {{db_pkg}} packages
yum:
name: "{{db_pkg}}" ##执行rescue模块
state: present
always:
- name: start ::db_service}} service
serbice:
name: "{{db_service}}" ##始终执行
state: started
设定变量 web_pkg: httpd,使block模块正常执行,忽略rescue模块,always总是执行