我正在使用 Ansible 的 shell 模块来查找特定字符串并将其存储在变量中。但是,如果 grep 没有找到任何东西,我会收到错误消息。
例子:
- name: Get the http_status
shell: grep "http_status=" /var/httpd.txt
register: cmdln
check_mode: no
当我运行这个 Ansible 剧本时,如果
http_status
字符串不存在,剧本已停止。我没有得到标准错误。
即使找不到字符串,如何让 Ansible 不间断地运行?
请您参考如下方法:
grep
如果未找到给定的字符串,则按设计返回代码 1。如果返回码不为 0,Ansible by design 会停止执行。您的系统工作正常。
要防止 Ansible 在此错误上停止 playbook 执行,您可以:
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 中描述了所有选项。文档。