当grep结果为空时,Ansible shell模块返回错误

当grep结果为空时,Ansible shell模块返回错误,grep,ansible,Grep,Ansible,我使用Ansible的shell模块查找特定字符串并将其存储在变量中。但如果格雷普没有发现任何东西,我就错了 例如: - name: Get the http_status shell: grep "http_status=" /var/httpd.txt register: cmdln check_mode: no 当我运行这个Ansible playbook时,如果http\u status字符串不存在,playbook就会停止。我不明白 即使找不到字符串,如何使Ansible

我使用Ansible的shell模块查找特定字符串并将其存储在变量中。但如果格雷普没有发现任何东西,我就错了

例如:

- name: Get the http_status
  shell: grep "http_status=" /var/httpd.txt
  register: cmdln
  check_mode: no
当我运行这个Ansible playbook时,如果
http\u status
字符串不存在,playbook就会停止。我不明白


即使找不到字符串,如何使Ansible运行不中断?

grep
by design如果找不到给定字符串,则返回代码1。如果返回代码与0不同,Ansible by design将停止执行。您的系统工作正常

要防止Ansible在此错误上停止playbook执行,您可以:

  • ignore\u错误:yes
    参数添加到任务中

  • 当:参数条件正确时,使用
    失败

由于
grep
为异常返回错误代码2,因此第二种方法似乎更合适,因此:

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

你也可以考虑添加<代码> CuxEd:当false ,这样任务不会被每次报告为“更改”。


文档中描述了所有选项。

正如您所观察到的,如果退出代码不为零,ansible将停止执行。您可以使用
ignore\u errors
忽略它

另一个技巧是通过管道将grep输出传输到
cat
。因此
cat
退出代码将始终为零,因为它的stdin是grep的stdout。如果有匹配项,也可以在没有匹配项时使用。试试看

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

我的问题如果为空,我还想运行ansible而不带interptionbonus points,包括通过failed_when进行的一些实际失败条件检测,以及使用changed_when:false的建议,以避免ansible输出中出现系统更改!