Ansible shell module returns error when grep results are empty

前端 未结 2 551
遇见更好的自我
遇见更好的自我 2020-12-01 12:33

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:

2条回答
  •  臣服心动
    2020-12-01 12:33

    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.

提交回复
热议问题