Ansible—— 34. playbook 錯誤處理

在編寫shell腳本時,有可能會有這樣的需求,當腳本執行到某個階段時,需要對某個條件進行判斷,如果條件成立,則立即終止腳本的運行,在 shell腳本中實現這個需求很簡單,只需要在條件成立時調用"exit"命令即可終止腳本的運行。
在執行playbook時,如果playbook中的任何一個任務執行失敗,playbook都會停止運行,除非這個任務設置 了"ignore_errors: true",在任務沒有設置"ignore_errors: yes"的情況下,任務執行失敗後,playbook就會自動終止,而fail模塊天生就是一個用來"執行失敗"的模塊,當fail模塊執行 後,playbook就會認爲有任務失敗了,從而終止運行。

---
- hosts: test70
  remote_user: root
  tasks:
  - debug:
      msg: "1"
  - debug:
      msg: "2"
  - fail:
  - debug:
      msg: "3"
  - debug:
      msg: "4"

當執行fail模塊時,fail模塊默認的輸出信息爲’Failed as requested from task’,我們可以通過fail模塊的msg參數自定義報錯的信息。

---
- hosts: test70
  remote_user: root
  tasks:
  - debug:
      msg: "1"
  - fail:
      msg: "Interrupt running playbook"
  - debug:
      msg: "2"

通常並不會毫無理由的想要去中斷playbook,通常需要對某些條件進行判斷, 如果條件滿足,則中斷劇本,所以,fail模塊通常與when結合使用,比如,如果之前模塊執行後的標準輸出信息中包含字符串’error’,則認爲中斷 劇本的條件成立,就立即調用fail模塊,以終斷playbook。

使用shell模塊故意輸出了一個包含’error’字符串的文本,並且將shell模塊執行後的返回值註冊到了變量’ return_value’中,在之後調用了fail模塊,並對fail模塊添加了判斷條件,對應的條件爲 “‘error’ in return_value.stdout”,這個條件表示shell模塊執行後的標註輸出信息中如果包含’error’字符串,則條件成立,其 中,'in’關鍵字的用法與python中’in’的用法相同,可以使用’in’關鍵字判斷一個字符串是否存在於另一個字符串中,也可以用於判斷一個特定 的值是否存在於列表中,由於shell標準輸出的信息中的確包含error字符串,所以fail模塊對應的條件成立,最終調用fail模 塊,playbook終止運行。不過需要注意的是,當使用"in"或者"not in"進行條件判斷時,整個條件需要用引號引起,並且,需要判斷的字符串也需要使用引號引起。

---
- hosts: test70
  remote_user: root
  tasks:
  - shell: "echo 'This is a string for testing--error'"
    register: return_value
  - fail:
      msg: "Conditions established,Interrupt running playbook"
    when: "'error' in return_value.stdout"
  - debug:
      msg: "I never execute,Because the playbook has stopped"

使用’in’或者’not in’進行條件判斷時,如下兩種語法是正確的:

when: ' "successful" not in return_value.stdout '
when: " 'successful' not in return_value.stdout "

‘failed_when’的作用就是,當對應的條件成立時,將對應任務的執行狀態設置爲失敗。一共有三個任務,第一個任務通過debug模塊輸出 “I execute normally”,第二個任務調用shell模塊,echo了’This is a string for testing error’這句話,並且將返回值註冊到了’return_value’變量中,’ failed_when’關鍵字與shell關鍵字對齊,表示其對應的條件是針對shell模塊的,’ failed_when’對應的條件是 ’ “error” in return_value.stdout’,表示"error"字符串如果存在於shell模塊執行後的標準輸出中,則條件成立,當條件成立 後,shell模塊的執行狀態將會被設置爲失敗,由於shell模塊的執行狀態被設置爲失敗,所以playbook會終止運行,於是,最後的debug模 塊並不會被執行。

---
- hosts: test70
  remote_user: root
  tasks:
  - debug:
      msg: "I execute normally"
  - shell: "echo 'This is a string for testing error'"
    register: return_value
    failed_when: ' "error" in return_value.stdout'
  - debug:
      msg: "I never execute,Because the playbook has stopped"

failed_when關鍵字的作用是在條件成立時,將對應任務的執行狀態設置爲失敗。changed_when關鍵字的作用是在條件成立時,將對應任務的執行狀態設置爲changed

---
- hosts: test70
  remote_user: root
  tasks:
  - debug:
      msg: "test message"
    changed_when: 2 > 1

————Blueicex 2020/3/28 11:32 [email protected]

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章