18

Ansible doesn't seem to be able to handle the result '0' for shell commands. This

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

Returns an error

"msg": "non-zero return code"

But when I replace "dev" with "type", which actually always occurs and gives a count of at least 1, then the command is successful and no error is thrown.

I also tried with command: instead of shell: - it doesn't give an error, but then the command is also not executed.

3 Answers 3

36

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
Sign up to request clarification or add additional context in comments.

3 Comments

Your answer is good in a strict way, and a good learning example. But for what I'm trying to do, realizing that there is the 'ansible fact' ansible_swaptotal_mb that immediately indicates whether there is a swap in the system or not, actually points to a better solution :)
i agree, i would prefer the ansible facts too if they can provide me the information i need :)
I believe that failed_when: is much better than ignore_errors: true! Thanks :)
2

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

Comments

0

You can also parse the grep count result in awk and return your custom output. This will avoid the ignore_errors module.

- name: Check if swap exists
  shell: "swapon -s | grep -ci dev" | awk '{ r = $0 == 0 ? "false":"true"; print r }'
  register: swap_exists

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.