How to kill a running process using ansible?

I have a boot game that allows you to kill running processes and works great most of the time!, From time to time we find processes that are simply impossible to kill, so "wait_for" goes to timeout, gives an error and it stops the process.

The current workaround is to manually go into the field, use "kill -9" and start the book you are listening to again, so I was wondering if there is a way to deal with this scenario from myself? I mean, do you want to use kill -9 from the very beginning, but may I have a way to handle the timeout ?, even use kill -9 only if the process was not killed in 300 seconds? but what would be the best way to do this?

These are the tasks that I currently have:

- name: Get running processes
  shell: "ps -ef | grep -v grep | grep -w {{ PROCESS }} | awk '{print $2}'"
  register: running_processes

- name: Kill running processes
  shell: "kill {{ item }}"
  with_items: "{{ running_processes.stdout_lines }}"

- name: Waiting until all running processes are killed
  wait_for:
    path: "/proc/{{ item }}/status"
    state: absent
  with_items: "{{ running_processes.stdout_lines }}"

Thank!

+4
source share
1 answer

You can ignore errors on wait_forand record the result in order to forcefully kill the defective elements:

- name: Get running processes
  shell: "ps -ef | grep -v grep | grep -w {{ PROCESS }} | awk '{print $2}'"
  register: running_processes

- name: Kill running processes
  shell: "kill {{ item }}"
  with_items: "{{ running_processes.stdout_lines }}"

- wait_for:
    path: "/proc/{{ item }}/status"
    state: absent
  with_items: "{{ running_processes.stdout_lines }}"
  ignore_errors: yes
  register: killed_processes

- name: Force kill stuck processes
  shell: "kill -9 {{ item }}"
  with_items: "{{ killed_processes.results | select('failed') | map(attribute='item') | list }}"
+10
source

Source: https://habr.com/ru/post/1686725/


All Articles