2016-12-07 72 views
10

我使用Ansible的shell模塊來查找特定字符串並將其存儲在變量中。但是,如果grep沒有找到任何東西,我得到一個錯誤。當grep結果爲空時,Ansible shell模塊返回錯誤

例子:

- name: Get the http_status 
    shell: grep "http_status=" /var/httpd.txt 
    register: cmdln 
    check_mode: no 

當我運行此Ansible劇本,如果http_status字符串是不存在的,劇本被停止。我沒有看到stderr。

即使找不到字符串,我如何使Ansible運行而不會中斷?

+0

我的問題,如果空還我想運行,而不爲,包括一些真正通過failed_when失效條件檢測interption – SSN

回答

11

就像你所觀察到的,如果grep退出代碼不爲零,ansible將停止執行。你可以用ignore_errors來忽略它。

另一個訣竅是將grep輸出傳輸到cat。因此,cat退出代碼將始終爲零,因爲它的stdin是grep的標準輸出。它有效,如果有匹配,也沒有匹配。嘗試一下。

- name: Get the http_status 
    shell: grep "http_status=" /var/httpd.txt | cat 
    register: cmdln 
    check_mode: no 
15

grep按設計返回代碼1如果找不到給定的字符串。如果返回代碼與0不同,Ansible by design停止執行。您的系統運行正常。

爲了防止Ansible從這個錯誤停止劇本執行,您可以:

  • ignore_errors: yes參數添加到任務

  • 使用failed_when:參數有適當的條件下

由於grep針對異常返回錯誤代碼2,因此第二種方法似乎更合適,因此:

- name: Get the http_status 
    shell: grep "http_status=" /var/httpd.txt 
    register: cmdln 
    failed_when: "cmdln.rc == 2" 
    check_mode: no 

您也可以考慮加入changed_when: false使爲「改變」每一次的任務將不會被報道。

所有選項都在Error Handling In Playbooks文檔中描述。

+0

獎勵積分的ansible,並使用changed_when的建議:false來避免系統變化的Ansible外觀輸出! –