2016-12-07 134 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外观输出! –