繁体   English   中英

使用pgrep的Ansible shell任务保持失败,在普通shell中工作

[英]Ansible shell task with pgrep keeps failing, works in normal shell

我在ansible-2.0.1.0-2.el7.noarch (但也试过1.9.4 )并且我正在尝试运行这个剧本:

- hosts: all
  remote_user: root
  tasks:
    - shell:
        pgrep --full 'sleep' && pkill --full 'sleep' || true

但我得到了:

# ansible-playbook -i aaa.ini aaa.yaml 

PLAY ***************************************************************************

TASK [setup] *******************************************************************
ok: [192.168.122.100]

TASK [command] *****************************************************************
fatal: [192.168.122.100]: FAILED! => {"changed": true, "cmd": "pgrep --full 'sleep' && pkill --full 'sleep' || true", "delta": "0:00:00.158772", "end": "2016-05-05 00:33:49.072139", "failed": true, "rc": -15, "start": "2016-05-05 00:33:48.913367", "stderr": "", "stdout": "385", "stdout_lines": ["385"], "warnings": []}

NO MORE HOSTS LEFT *************************************************************
    to retry, use: --limit @aaa.retry

PLAY RECAP *********************************************************************
192.168.122.100               : ok=1    changed=0    unreachable=0    failed=1

当我直接运行命令时,它可以工作:

host # ssh root@192.168.122.100
vm # pgrep --full 'sleep' && pkill --full 'sleep' || true
vm # echo $?
0

请问你对我做错了什么?

按照@ Dag的回答更新 ,这对我来说是破译的:

$ ansible localhost -m shell -a "pgrep --list-full -f process_that_does_not_exists"
localhost | SUCCESS | rc=0 >>
828 /usr/bin/python /usr/bin/ansible localhost -m shell -a pgrep --list-full -f process_that_does_not_exists
835 /usr/bin/python /usr/bin/ansible localhost -m shell -a pgrep --list-full -f process_that_does_not_exists
836 /usr/bin/python /usr/bin/ansible localhost -m shell -a pgrep --list-full -f process_that_does_not_exists

所以带有&& pkill ...的命令&& pkill ...实际上是在杀死一些Ansible的进程。 看起来我必须添加一些过滤才能安全地工作。

从输出中可以看出,命令返回-15。 这意味着该流程已终止。

如果我在localhost上执行你的命令,我实际上是在杀死我自己的ansible运行。

[dag@moria ~]$ ansible localhost -m shell -a 'pgrep -f 'sleep' && pkill -f 'sleep' || true'
Terminated

所以你从一个剧本中做同样的事情,并且正在杀死Ansible的一部分进程,但不是太多,所以它可以正确地报告一些输出和返回代码。 (我实际上也在我自己的系统上杀死了主要的调用进程!)

我遇到了类似的问题,并通过将脚本放入.sh文件并执行sh xxx.sh修复它。

只是抬头,在ansible中使用scriptcommand模块而不是shell的最佳做法可能是最好的做法: Notes - shell - 在节点中执行命令

Ansible的shell模块运行脚本(或等效)

bash -c "your-whole-script-as-one-quoted-string"

因此,如果您的脚本包含pkill -f killpattern它不仅会匹配您要杀死的进程,还会匹配运行pkill命令的shell进程 - 即ansible步骤本身。

要解决这个问题,你需要做这样的事情:

for i in $(pgrep -f killpattern | grep -v -x $$) ; do kill $i ; done

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM