首先,一个任务执行失败是肯定会遇见的事情
而这时候,就需要一个备用的计划
忽略任务失败
默认情况下 任务失败的时候play会终止
但是,我们可以通过忽略失败的任务来覆盖此行文
使用关键字 ignore_errors
举个栗子
- name: Latest version of notapkg is installed
yum:
name: notapk
state: latest
ignore_errors: yes
因为不存在notapk所以任务会执行,play会终止 但是,
在该任务中使用ignore_errors,在任务失败时也将继续在主机上执行playbook
任务失败后强制执行处理程序
使用force_handlers关键字,在任务失败的时候强制执行
---
- hosts: all
force_handlers: yes
tasks:
- name: a task which always notifies its handler
command: /bin/true
notify: restart the database
- name: a task which fails because the package doesnot exist
yum:
name: notapk
state: latest
handlers:
- name: restart the database
service:
name: mariadb
state: restarted
处理程序会在任务报告changed结果时获得通知,而在报告ok或failed时不会获得通知
指定任务失败的条件
使用关键字failed_when


处理错误
使用 rescue和always语句来处理错误
如果块中的任何任务失败,则执行rescue块中的任务
在block子句中的任务或者rescue子句中的任务运行之后 always子句中的任务将会运行
反正always的语句总会执行的

tasks:
- name: Upgrade DB
block:
- name: Upgrade the database
shell:
cmd: /usr/local/lib/upgrade-database
rescue:
- name: revert the database upgrade
shell:
cmd: /usr/local/lib/revert-database
always:
- name: always restart the database
service:
name: mariadb
state: restarted
处理任务失败实验

1.实验开始 lab control-errors start
2.去往实验文件夹并且 创建 ansible配置文件 和一个服务器(包含服务器
servera.lab.example.com在databases组当中)
3.创建playbook

初始状态如下

运行playbook

此时因为不存在名为http的现有安装包,所以第一个任务失败了,因此第二个任务也没有运行
更新playbook

再次运行playbook

再次更新playbook 添加block内容



再次更新playbook 更正web_package的值 为httpd
并且再次运行





如果再次运行该playbook check local time 任务将再次返回changed


运行playbook



执行结果


完成实验 lab control-errors finish