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.