Ansible: How force kill process and exit from ansible-playbook if not successful?

cn flag

I have two bellow tasks as part from my playbook

      - name: "Verify httpd.service no running on node {{ ansible_hostname }}"
        shell: "ps -ef | grep httpd"
        register: _ps_httpd
        become: true
      - name: stop httpd is exit code eq to 0
        shell: "kill -9 $(ps -ef | grep httpd| awk '{print $2}')"
        when: _ps_httpd.rc == 0
        become: true
        ignore_errors: true

This two tasks that should force kill process. Currently I'm getting the error

"msg": "non-zero return code", "rc": -9

What do I miss here? Any idea how to get resolve this?

In addition, I would like to add the option exit from ansible-playbook run if not successful.

ca flag

To achieve the goal in Ansible it is recommended in general to use service modules, service, sysvinit or systemd. In example like

- hosts: localhost
  become: yes
  become_method: sudo

  gather_facts: yes


  - name: Gathering Service Facts

  - name: Make sure service is stopped
      name: httpd
      state: stopped
      enabled: no
    when: ("httpd.service" in services)

If you like to use the shell_module, for me more work was necessary.

In example for nginx get the right PID first, since there are a primary and four worker processes.

- name: Get nginx PID
    cmd: "ps -C nginx -o pid --no-headers | head 1"
    warn: false
  changed_when: false
  check_mode: false
  register: nginx_pid

It would also be possible to do something like

- name: Get nginx PIDs
    cmd: "pidof nginx"
    warn: false
  changed_when: false
  check_mode: false
  register: nginx_pids

- name: Show PIDs
    var: nginx_pids

- name: Kill nginx
    cmd: "kill -9 {{ nginx_pids }}"


I would like to add the option exit from ansible-playbook run if not successful.

to end the playbook run you could use

- meta: end_play
  when: condition_is_met

use fail_module to

- name: Task has failed because of
    msg: "{{ fail_message }}"
  when: condition_is_met

or the assert_module.

Regarding the exit code (EC) or return code (RC) you may have a look into How do I get the list of exit codes (and/or return codes) and meaning for a command/utility?.

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.