簡體   English   中英

從同一 playbook 中獲取 ansible playbook 的 PID

[英]Get the PID of ansible playbook from within the same playbook

我正在嘗試從劇本中獲取 ansible 劇本的 PID。 我找到了一種粗略的方法,我正在努力使其更加精致和強大。 如果我按照find + awk命令運行,它會給我用戶提供的ansible-playbook的所有 PID。 盡管它也給了我一些虛假的 PID,但我需要刪除它們。

例如:4229 是一個有效的 PID,我需要它,而 19425 是一個陳舊的 PID(不存在於 ps -eaf 輸出中),我需要將它從我的列表中刪除。

要直觀地查看其中包含 PID 名稱的文件:

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 是否存在:

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,因為 19425 從ps -eaf output 中消失了。

問題:

如何有效地結合findawkps -eaf命令來生成 output 4229

順便說一句,我嘗試了Get the pid of a running playbook 中提供的更簡單的解決方案,以便在 playbook 中使用,甚至增加了賞金,但還沒有樂趣。 因此,請不要將其標記為重復,因為這是對該問題的擴展。

嘗試這個:

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

由於您已經有一個關於在劇本中運行劇本的問題,我將解決您的另一個問題。

正如 Andrew 建議的那樣,我認為如果您想消除過時的 Ansible 鎖,解析鎖目錄比從進程表開始更有意義。 這將是我的看法:

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

這基本上說:

  • 對於每個 Ansible 文件,
    • 從文件名中提取pid,
    • 使用ps查看該 pid 的進程是否正在運行,並且
    • 如果不是,請刪除該文件。

剩下的就是一個有效的過程。 (雖然這並不能保證它是一個 ansible 進程。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM