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總是執行