How to kill a running process using ansible?
The killall
command has a wait option that might be useful.
Install psmisc:
tasks:
- apt: pkg=psmisc state=present
Then use killall like this:
tasks:
- shell: "killall screen --wait"
ignore_errors: true # In case there is no process
-w, --wait
:
Wait for all killed processes to die. killall checks once per second if any of the killed processes still exist and only returns if none are left.
Use pkill
(1) instead of grep
+kill
.
You could ignore errors on wait_for
and register the result to force kill failed items:
- 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 }}"