Score:0

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.

Score:0
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

  tasks:

  - name: Gathering Service Facts
    service_facts:

  - name: Make sure service is stopped
    systemd:
      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
  shell:
    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
  shell:
    cmd: "pidof nginx"
    warn: false
  changed_when: false
  check_mode: false
  register: nginx_pids

- name: Show PIDs
  debug: 
    var: nginx_pids

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

Regarding

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
  fail:
    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?.

mangohost

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.