我正在使用Ansible的shell模块来查找特定字符串并将其存储在变量中。但是如果grep没找到任何东西我会收到错误。
示例:
- name: Get the http_status
shell: grep "http_status=" /var/httpd.txt
register: cmdln
check_mode: no
当我运行此Ansible剧本时,如果http_status
字符串不存在,则播放本已停止。我没有得到stderr。
即使找不到字符串,如何在不中断的情况下运行Ansible?
答案 0 :(得分:39)
grep
按设计返回代码1。如果返回代码不同于0,则设计Ansible将停止执行。您的系统正常运行。
为了防止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文档中描述了所有选项。
答案 1 :(得分:19)
如您所观察到的,如果grep
退出代码不为零,则ansible将停止执行。您可以使用ignore_errors
忽略它。
另一个技巧是将grep输出传递给cat
。所以cat
退出代码将始终为零,因为它的标准输入是grep的标准输出。如果匹配并且没有匹配时它可以工作。试试吧。
- name: Get the http_status
shell: grep "http_status=" /var/httpd.txt | cat
register: cmdln
check_mode: no