##处理任务失败
通常playbook遇到错误会中止执行,但是有时我们想要失败时也继续执行
##忽略任务失败
关键字:ignore_errors
#举例
[root@workstationcode]#cat ignore.yml
---
- name: Test
hosts: webservers
tasks:
- name: Install package
yum:
name: k8s
state: latest
ignore_errors: yes
#执行
[root@workstationcode]#ansible-playbook ignore.yml
...
TASK[Installpackage]*********************************************************
fatal:[servera.lab.example.com]:FAILED!=>{"changed":false,"failures":["No
packagek8savailable."],"msg":"Failedtoinstallsomeofthespecifiedpackages",
"rc":1,"results":[]}
...ignoring
##任务失败后强制执行处理程序
通常任务失败,play会中止,那么收到play中之前任务通知的处理程序将不会运行,如果要运
行,需要使用关键字:force_handlers: yes
#举例
[root@workstationcode]#cat force.yml
---
- hosts: webservers
force_handlers: yes
tasks:
- name: always notify
command: /bin/true
notify: restart apache
- name: Fail task
yum:
name: k8s
state: latest
handlers:
- name: restart apache
service:
name: httpd
state: restarted
'处理程序会在任务报告changed结果时获得通知,ok或者failed都不会'
##指定任务失败条件
关键字:failed_when
tasks:
- name: Run Script
shell: /usr/local/bin/user.sh
register: command_result
failed_when: "'failure'incommand_result.stdout"
#fail模块可以实现此效果
tasks:
- name: Run Script
shell: /usr/local/bin/user.sh
register:command_result
ignore_error: yes
- name: Report failure
fail:
msg: "Authenticationfailure" #fail模块可以提供明确消息
when: "'failure'incommand_result.stdout"
##指定任务何时报告"Changed"结果
关键字:changed_when
#
- name: get time
shell: date
changed_when: false
##ansible块和错误处理
三种关键字:
block:定义要运行的主要任务
rescue:定义要在block子句中定义的任务失败时运行的任务
always:定义时中独立运行的任务
#练习:
故意制造错误
[root@workstationcode]#cat error.yml
---
- name: Task Failure
hosts: webservers
vars:
web_pkg: http
db_pkg: mariadb-server
db_service: mariadb
tasks:
- name: Install {
{ web_pkg }} packages
yum:
name: "{
{ web_pkg }}"
state: present
- name: Install {
{ db_pkg }} packages
yum:
name: "{
{ db_pkg }}"
state: present
运行报错
[root@workstationcode]#ansible-playbook error.yml
...
TASK[Installhttppackages]***************************************************
fatal:[servera.lab.example.com]:FAILED!=>{"changed":false,"failures":["No
packagehttpavailable."],"msg":"Failedtoinstallsomeofthespecifiedpackages",
"rc":1,"results":[]}
第一个任务失败,第二个任务不运行
#添加忽略关键字
[root@workstationcode]#vim error.yml
...
13ignore_errors:yes
---
- name: Task Failure
hosts: webservers
vars:
web_pkg: http
db_pkg: mariadb-server
db_service: mariadb
tasks:
- name: Install {
{ web_pkg }} packages
yum:
name: "{
{ web_pkg }}"
state: present
ignore_errors: yes
- name: Install {
{ db_pkg }} packages
yum:
name: "{
{ db_pkg }}"
state: present
#使用block、rescue、always将任务分开
[root@workstationcode]#cat error.yml
---
- name: Task Failure
hosts: webservers
vars:
web_pkg: http
db_pkg: mariadb-server
db_service: mariadb
tasks:
- name: Setup Web