I am using Ansible's shell module to find a particular string and store it in a variable. But if grep did not find anything I am getting an error.
Example:
- name: Get the http_status
shell: grep "http_status=" /var/httpd.txt
register: cmdln
check_mode: no
When I run this Ansible playbook if http_status
string is not there, playbook is stopped. I am not getting stderr.
How can I make Ansible run without interruption even if the string is not found?
Like you observed, ansible will stop execution if the
grep
exit code is not zero. You can ignore it withignore_errors
.Another trick is to pipe the grep output to
cat
. Socat
exit code will always be zero since its stdin is grep's stdout. It works if there is a match and also when there is no match. Try it.grep
by design returns code 1 if the given string was not found. Ansible by design stops execution if the return code is different from 0. Your system is working properly.To prevent Ansible from stopping playbook execution on this error, you can:
add
ignore_errors: yes
parameter to the taskuse
failed_when:
parameter with a proper conditionBecause
grep
returns error code 2 for exceptions, the second method seems more appropriate, so:You might also consider adding
changed_when: false
so that the task won't be reported as "changed" every single time.All options are described in the Error Handling In Playbooks document.