Roman Gaufman
Roman Gaufman

Reputation: 1124

Why does Ansible think this shell command has a non-zero return code?

I have this recipe:

- name: Kill usr/bin/perl -w /usr/share/debconf/frontend
  shell: "{{ item }}"
  with_items:
    - 'pkill -9 -f debconf/frontend || echo'
  changed_when: false # Don't report changed state

When I run this on the command line, it returns a 0 exit code thanks to || echo:

~$ pkill -9 -f debconf/frontend || echo

~$ $?
0

However running in Ansible it shows this:

failed: [testhost1] (item=pkill -9 -f debconf/frontend || echo) => {"ansible_loop_var": "item", "changed": false, "cmd": "pkill -9 -f debconf/frontend || echo", "delta": "0:00:00.132296", "end": "2023-01-13 10:34:11.098765", "item": "sudo pkill -9 -f debconf/frontend || echo", "msg": "non-zero return code", "rc": -9, "start": "2023-01-13 10:34:10.966469", "stderr": "", "stderr_lines": [], "stdout": "", "stdout_lines": []}

Any ideas what I'm doing wrong?

Upvotes: 0

Views: 784

Answers (2)

U880D
U880D

Reputation: 12017

Starting a test process via

perl -MPOSIX -e '$0="test"; pause' &

a minimal example playbook

---
- hosts: localhost
  become: false
  gather_facts: false

  tasks:

  - name: Shell task
    shell:
      cmd: "{{ item }}"
    with_items:
      - 'pkill -9 -f test || echo'
    register: result

  - name: Show result
    debug:
      msg: "{{ result }}"

reproduce the issue. Using instead

    with_items:
      - 'pkill -9 -f test'

or

    with_items:
      - 'kill -9 $(pgrep test) || echo'

will execute without an error.

Links

Similar Q&A

with the same error message

Further Reading

Since it is recommended to use Ansible modules instead of shell commands if possible

---
- hosts: localhost
  become: false
  gather_facts: false

  tasks:

  - name: Get Process ID (PID)
    pids:
      name: test
    register: PID

  - name: Show PID
    debug:
      msg: "{{ PID.pids | first }}"

  - name: Shell task
    shell:
      cmd: "kill -9 {{ PID.pids | first }}"
    register: result

  - name: Show result
    debug:
      msg: "{{ result }}"

Upvotes: 1

Roman Gaufman
Roman Gaufman

Reputation: 1124

Ah, this is because running pkill from inside of Ansible causes it to kill itself (bug in pkill?)

In any case, a workaround is to do this:

  with_items:
    - 'if pgrep -f "debconf/frontend" | grep -v $$; then sudo pkill -9 -f "debconf/frontend"; fi'

Upvotes: 1

Related Questions