shell - Ansible playbook shell 输出

标签 shell sed ansible

我想使用 ansible-playbook 使用 ps、dstat 等命令快速监控一些主机。 ansible 命令本身完美地满足了我的需求,例如我会使用:

ansible -m shell -a "ps -eo pcpu,user,args | sort -r -k1 | head -n5"

它很好地打印了每个主机的所有 std 输出,如下所示:

localhost | success | rc=0 >>
0.0 root     /sbin/init
0.0 root     [kthreadd]
0.0 root     [ksoftirqd/0]
0.0 root     [migration/0]

otherhost | success | rc=0 >>
0.0 root     /sbin/init
0.0 root     [kthreadd]
0.0 root     [ksoftirqd/0]
0.0 root     [migration/0] 

但是,这需要我为每个任务保留一堆 shell 脚本,这不是很“可靠”,所以我将其放入剧本中:

---
-
  hosts: all
  gather_facts: no
  tasks:
    - shell: ps -eo pcpu,user,args | sort -r -k1 | head -n5

并使用-vv运行它,但输出基本显示字典内容并且换行符不会这样打印,因此这会导致像这样的不可读的困惑:

changed: [localhost] => {"changed": true, "cmd": "ps -eo pcpu,user,args | sort -r -k1 
head -n5 ", "delta": "0:00:00.015337", "end": "2013-12-13 10:57:25.680708", "rc": 0,
"start": "2013-12-13 10:57:25.665371", "stderr": "", "stdout": "47.3 xxx    Xvnc4 :24
-desktop xxx:24 (xxx) -auth /home/xxx/.Xauthority -geometry 1920x1200\n
.... 

我还尝试添加 register: var 和“调试”任务来显示 {{ var.stdout }} 但结果当然是相同的。

当通过剧本运行时,有没有办法从命令的 stdout/stderr 获得格式良好的输出?我可以想到多种可能的方法(使用 sed 格式化输出?将输出重定向到主机上的文件,然后取回该文件并将其回显到屏幕上?),但由于我对 shell/ansible 的了解有限,这需要我有一天尝试一下。

最佳答案

debug 模块确实需要一些爱,但目前你能做的最好的就是使用这个:

- hosts: all
  gather_facts: no
  tasks:
    - shell: ps -eo pcpu,user,args | sort -r -k1 | head -n5
      register: ps

    - debug: var=ps.stdout_lines

它给出这样的输出:

ok: [host1] => {
    "ps.stdout_lines": [
        "%CPU USER     COMMAND",
        " 1.0 root     /usr/bin/python",
        " 0.6 root     sshd: root@notty ",
        " 0.2 root     java",
        " 0.0 root     sort -r -k1"
    ]
}
ok: [host2] => {
    "ps.stdout_lines": [
        "%CPU USER     COMMAND",
        " 4.0 root     /usr/bin/python",
        " 0.6 root     sshd: root@notty ",
        " 0.1 root     java",
        " 0.0 root     sort -r -k1"
    ]
}

关于shell - Ansible playbook shell 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20563639/

相关文章:

regex - sed 中的正则表达式不起作用

ansible:变量未使用角色重新初始化

c - 该命令在 C 中有效吗?

linux - SED:摘自谷歌财经

外部脚本函数上的 bash 命令替换收到不正确的退出状态

linux - 如何编辑段落中的设置?

Ansible 始终运行角色

loops - Ansible 和循环中的嵌套变量

c - C 中的 Tee 函数调用不起作用而不是 tee 命令

bash - 将 MAC 地址读取到 shell 变量会导致奇怪的行为