从同一个剧本中获取ansible剧本的PID [英] Get the PID of ansible playbook from within the same playbook

查看:226
本文介绍了从同一个剧本中获取ansible剧本的PID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从剧本中获取ansible剧本的PID.我找到了一种粗略的方法,我试图使其更加精致和强大.如果我按照find + awk命令运行,它将为用户提供ansible-playbook的所有PID.尽管它也给了我一些伪造的PID,但我需要删除它们.

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.

例如:4229是有效的PID,我需要它,而19425是陈旧的PID(在ps -eaf输出中不存在),我需要将其从列表中删除.

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.

要直观地查看其中带有PID名称的文件:

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>

要提取PID名称:

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

要验证PID是否有效:

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:~>

只希望得出4229,因为从ps -eaf输出中删除了19425.

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

问题:

如何有效地组合findawkps -eaf命令以生成输出4229?

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.

推荐答案

尝试一下:

#!/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' )

如果正确列出了过时的目录,则在第6行中将ls -lad更改为'rm -r`.

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

这篇关于从同一个剧本中获取ansible剧本的PID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆