Ansible error on shell command returning zero

since you want to run a sequence of commands that involve pipe, ansible states you should use shell and not command, as you are doing.

So, the problem is the fact that grep returns 1 (didnt find a match on the swapon output), and ansible considers this a failure. Since you are well sure there is no issue, just add a ignore_errors: true and be done with it.

- name: Check if swap exists
  shell: "swapon -s | grep -ci non_existent_string"
  register: swap_exists
  ignore_errors: true

OR:

if you want to narrow it down to return codes 0 and 1, instruct ansible to not consider failures those 2 rcs:

- name: Check if swap exists
  shell: "swapon -s | grep -ci non_existent_string"
  register: swap_exists
  # ignore_errors: true
  failed_when: swap_exists.rc != 1 and swap_exists.rc != 0

I found a better way. if you only need to know the record number this works:

- name: Check if swap exists
  shell: "swapon -s | grep -i dev|wc -l"
  register: swap_exists

Another way is to always use cat at the end of the pipe. See Ansible shell module returns error when grep results are empty

    - name: Check if swap exists
      shell: "swapon -s | grep -i dev|cat"
      register: swap_exists

Tags:

Ansible