Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
663 views
in Technique[技术] by (71.8m points)

Ansible shell module returns error when grep results are empty

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 task

  • use failed_when: parameter with a proper condition

Because grep returns error code 2 for exceptions, the second method seems more appropriate, so:

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...