monk
monk

Reputation: 2115

Get the PID of ansible playbook from within the same playbook

I am trying to get the ansible playbook's PID from within the playbook. I found one crude approach, I am trying to make it more refined and robust. If I run following find + awk command, it gives me all the PID of ansible-playbook by the user. Although it give me few bogus PIDs as well and I need to remove them.

For example: 4229 is a valid PID and I need it whereas 19425 is a stale PID(not present in ps -eaf output) and I need to remove it from my list.

To visually see the files with PID names in them:

meta@monk:~/.ansible/tmp>ls -lrt
total 8
drwx------ 2 monk admin4096 Oct 16 13:09 ansible-local-19425A_62FT
drwx------ 3 monk admin4096 Oct 17 10:38 ansible-local-4229U_pXdg
meta@monk:~/.ansible/tmp>

To extract the PID names:

meta@monk:~/.ansible/tmp>find . -type d |awk 'NR>1{pid=gensub(/.\/ansible-local-([0-9]+)._.*$/,"\\1","g",$NF);print pid}'
4229
4229
19425

To validate if a PID is alive or not:

meta@monk:~>ps -eaf |grep -iE '4229|4229|19425'
monk   4229  2179  5 10:33 pts/26   00:00:49 /usr/local/bin/python /usr/local/bin/ansible-playbook pid.yml -vv
monk   5303  4229  0 10:38 pts/26   00:00:00 /usr/local/bin/python /usr/local/bin/ansible-playbook pid.yml -vv
monk   5744  5569  0 10:49 pts/3    00:00:00 grep -iE 4229|4229|19425
meta@monk:~>

Concluding only 4229 is desired, as 19425 is gone from ps -eaf output.

Question:

How to combine find , awk, and ps -eaf command efficiently to produce the output 4229?

By the way, I tried simpler solutions provided in Get the pid of a running playbook for use within the playbook ,even added bounty but no joy yet. So please do not mark it as duplicate as this is an extension to that question.

Upvotes: 0

Views: 719

Answers (2)

ghoti
ghoti

Reputation: 46856

Since you've already got a question going about running a playbook within a playbook, I'll address your other question.

As Andrew suggested, I think if you want to eliminate your stale Ansible locks, it makes more sense to parse the lock directory than to start with your process table. This would be my take on it:

for f in ~/.ansible/tmp/ansible-local-*; do
  [[ $f =~ .*-([0-9]+) ]]
  pid="${BASH_REMATCH[1]}"
  ps "$pid" >/dev/null || rm -vf "$f"
done

This basically says:

  • For each Ansible file,
    • extract the pid from the filename,
    • use ps to see if a process by that pid is running, and
    • if it is not, delete the file.

Whatever remains is a valid process. (Though this doesn't guarantee that it's an ansible process.)

Upvotes: 1

Andrew Vickers
Andrew Vickers

Reputation: 2654

Try this:

#!/bin/bash

cd ~/.ansible/tmp

while read pid; do
  [ -d /proc/${pid} ] || ls -lad ansible-local-${pid}*;
done < <(find . -type d | sed -n 's/^ansible-local-\([0-9]*\).*$/\1/p' )

If correctly lists the stale directories, then change ls -lad to 'rm -r` in line 6.

Upvotes: 1

Related Questions