处理程序
处理程序是非活动任务,只有notify语句调用时候才会运行handlers中的任务,而notify只有template任务通知发生改变的时候才会触发,也就是报告changed状态,否则会直接跳过notify
tasks:
- name: copy configuration templatetemplate:
src: /var/lib/templates/demo .dest:/etc/httpd//
notify:
- restart mysqlhandlers:
- name: restart mysqlservice:
name: mariadbstate: restarted
处理任务失败
通常情况,当任务失败时,ansible将立即在主机上终止play的其余部分并且跳过后续所有任务
但我们也可以忽略任务失败
忽略任务失败
可以使用ignore_errors关键字来实现此目的,将其设定为yes,yum执行失败,也会继续执行后续内容
yum:
name: http
state: latest
ignore_errors: yes
任务失败后执行处理程序
通常情况任务失败play会从主机终止,并且任务通知中的处理程序也不会运行。但是可以设置force_handlers: yes关键字,即使play失败而终止,也会调用处理程序
---
- hosts: all
force_handlers: yestasks:
- name: a task which always notifies its handler
command:/bin/true
notify: restart the database
- name: a task which fails because the package doesn't existyum:
name: notapkg
state: latest
handlers:
- name: restart the databaseservice:
name: mariadbstate:restarted
指定任务失败条件
你可以在任务中使用failed_when关键字来指定表示任务已失败的条件。
tasks:
- name: Run user creation script
shell:/usr/local/bin/create_users.shregister: command_result
failed_when: "'Password missing' in command_result.stdout"
只有当'Password missing'存在于command_result中时才会任务失败
指定何时任务报告changed结果
changed_when关键字可用于控制任务在何时报告他已进行了更改。
changed_when=false时那他只报告ok或者failed
也可以使用条件来进行输出报告
changed_when="'RadHat'== ansible_distribution"
Ansible块和错误处理
块是对任务进行逻辑分组的子句,可用于控制任务的执行方式。
块可以借个rescue和always语句来处理错误
block:定义要运行的主要任务。在block的when条件也会应用在其rescue和always语句中
rescue:定义要在block子句中定义的任务失败时运行的任务。
always:定义始终都独立运行的任务,不论block和rescue子句中定义的任务是成功还是失败。
tasks:
-name: Upgrade DBblock:
-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 databaseservice:
name: mariadbstate: restarted