fail模組場景(ansible)
更多見部落格 : //blog.csdn.net/qq_35887546/article/details/105242720
創建劇本 /home/alice/ansible/lvm.yml,用來為所有受管機完成以下部署:
-
1)在卷組 search 中創建名為 mylv 的邏輯卷,大小為 1000MiB
-
2)使用 ext4 文件系統格式化該邏輯卷
-
3)如果無法創建要求的大小,應顯示錯誤資訊 insufficient free space,並改為 500MiB
-
4)如果卷組 search 不存在,應顯示錯誤資訊 VG not found
-
5)不需要掛載邏輯卷
一、fail模組
在編寫shell腳本時,有可能會有這樣的需求,當腳本執行到某個階段時,需要對某個條件進行判斷,如果條件成立,則立即終止腳本的運行,在shell腳本中實現這個需求很簡單,只需要在條件成立時調用”exit”命令即可終止腳本的運行, 那麼在編寫playbook時,如果有類似的需求,我們該怎麼辦呢?
想要在playbook中按照我們的意願中斷劇本的執行,其實也很簡單,我們只需要藉助一個模組即可完成,這個模組就是”fail”模組。
我們知道,在執行playbook時,如果playbook中的任何一個任務執行失敗,playbook都會停止運行,除非這個任務設置了”ignore_errors: true”,在任務沒有設置”ignore_errors: true”的情況下,任務執行失敗後,playbook就會自動終止,而fail模組天生就是一個用來”執行失敗”的模組,當fail模組執行後,playbook就會認為有任務失敗了,從而終止運行,實現我們想要的中斷效果,來看一個小示例:
[root@server4 ~]# vim block4.yml [root@server4 ~]# cat block4.yml --- - hosts: testB remote_user: root tasks: - debug: msg: "1" - debug: msg: "2" - fail: - debug: msg: "3" - debug: msg: "4"
如上例所示,上例playbook中一共有4個debug任務,在第2個debug任務之後,我們調用了fail模組,那麼我們來運行一下上例playbook,執行後輸出資訊如下
從上圖可以看出,當前兩個debug模組輸出了對應的資訊後,playbook報錯了,之後的debug模組並未被調用,實現了中斷劇本運行的效果,當執行fail模組時,fail模組默認的輸出資訊為』Failed as requested from task』,我們可以通過fail模組的msg參數自定義報錯的資訊,示例如下
[root@server4 ~]# vim block5.yml
[root@server4 ~]# cat block5.yml --- - hosts: testB remote_user: root tasks: - debug: msg: "1" - fail: msg: "Interrupt running playbook" - debug: msg: "2"
當然,上述示例只是為了初步介紹fail模組的用法,我們通常並不會毫無理由的想要去中斷playbook,通常需要對某些條件進行判斷,如果條件滿足,則中斷劇本,所以,fail模組通常與when結合使用,比如,如果之前模組執行後的標準輸出資訊中包含字元串』error』,則認為中斷劇本的條件成立,就立即調用fail模組,以終斷playbook,示例如下:
[root@server4 ~]# vim fail1.yml [root@server4 ~]# cat fail1.yml --- - hosts: testB 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"
上例中,我們使用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”進行條件判斷時,整個條件需要用引號引起,並且,需要判斷的字元串也需要使用引號引起,所以,使用』in』或者』not in』進行條件判斷時,如下兩種語法是正確的:
when: ' "successful" not in return_value.stdout ' when: " 'successful' not in return_value.stdout "