Ansible shell module returns error when grep results are empty

Question:

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:

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?

Answer:

Like you observed, ansible will stop execution if the grep exit code is not zero. You can ignore it with ignore_errors.

Another trick is to pipe the grep output to cat. So cat 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.

Leave a Reply