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

时间:2016-12-07 05:56:23

标签: grep ansible

我正在使用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?

2 个答案:

答案 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