Wait for processes to end with Ansible

I’ve been doing a lot in stuff in ansible recently where I needed to fire up, kill and relaunch a bunch of processes. I wanted to find a quick and reliable way of managing this…

This is possible using a combination of the pids and wait_for modules…

First get the pids of your process…

- name: Getting pids for mongod
  pids:
      name: mongod
  register: pids_of_mongod

The pids module returns a list with which we can iterate over with with_items.Then we can use the wait_for task and the /proc filesystem to ensure all the processes have exited…

- name: Wait for all mongod processes to exit
  wait_for:
    path: "/proc/{{ item }}/status"
    state: absent
  with_items: "{{ pids_of_mongod.pids }}"

After this last task complete you can be sure that the Linux OS has cleaned up all your processes.

Leave a Reply