Playbook忽略错误
默认playbook会检测task执行的返回状态,如果遇到错误则会立即终止playbook的后续task执行,然鹅有些时候playbook即使执行错误了也要让其继续执行。
加入参数:ignore_errors:yes 忽略错误
[root@m01 ~]# cat ignore.yml
---
- hosts: all
tasks:
- name: Ignore False
command: /bin/false
ignore_errors: yes
- name: touch new file
file:
path: /tmp/lzd.txt
state: touch
playbook错误处理
如上所述,当task执行失败时,playbook将不再继续执行,包括如果在task中设置了handler也不会被执行。
但是我们可以采取强制措施...
### 强制调用handler
[root@m01 ~]# cat handler.yml
- hosts: web_group
vars:
- http_port: 8080
force_handlers: yes ### 强制调用
tasks:
- name: config httpd server
template:
src: ./httpd.j2
dest: /etc/httpd/conf
notify:
- Restart Httpd Server
- Restart PHP Server
- name: Install Http Server
apt:
name: nginx
state: present
- name: start httpd server
service:
name: nginx
state: started
enabled: yes
handlers:
- name: Restart Httpd Server
systemd:
name: nginx
state: restarted
- name: Restart PHP Server
systemd:
name: php-fpm
state: restarted
### 抑制changed
被管理主机没有发生变化,可以使用参数将change状态改为ok
[root@m01 ~]# cat handler.yml
- hosts: web_group
vars:
- http_port: 8080
force_handlers: yes
tasks:
- name: shell
shell: netstat -lntup|grep httpd
register: check_httpd
changed_when: false
- name: debug
debug: msg={{ check_httpd.stdout.lines }}
cat changed_when.yml
- hosts: aa_group
vars:
- http_port: 8080
tasks:
- name: configure httpd server
template:
src: ./httpd.j2
dest: /etc/httpd/conf/httpd.conf
notify: Restart Httpd Server
- name: Check HTTPD
shell: /usr/sbin/nginx -t
register: httpd_check
changed_when:
- httpd_check.stdout.find('OK')
- false
- name: start httpd server
service:
name: httpd
state: started
enabled: yes
handlers:
- name: Restart Httpd Server
systemd:
name: httpd
state: restarted
###########
- name: Check HTTPD
shell: /usr/sbin/httpd -t
register: httpd_check
changed_when:
- httpd_check.stdout.find('OK')
- false
使用 shell 模块运行 HTTPD 的语法检查命令 /usr/sbin/httpd -t。
结果保存在 httpd_check 变量中。
changed_when 语句用于确定该任务是否被视为更改。这里的逻辑是:如果输出中包含 "OK",则不视为更改。