Ansible:shell 脚本输出始终为空

2024-04-11

我试图将 Linux shell 的输出插入到变量中,但由于某种原因,该变量始终为空。

这是 Ansible 代码:

  - name: Check PHP version
    shell: php -v 2> /dev/null | awk '{print $2; exit}'
    register: php_version

  - debug: var=php_version

这是输出:

ok: [10.0.0.5] => {
    "php_version": {
        "changed": true, 
        "cmd": "php -v 2> /dev/null | awk '{print $2; exit}'", 
        "delta": "0:00:00.015180", 
        "end": "2017-01-08 18:41:00.323773", 
        "rc": 0, 
        "start": "2017-01-08 18:41:00.308593", 
        "stderr": "", 
        "stdout": "", 
        "stdout_lines": [], 
        "warnings": []
    }
}

当我直接在服务器上运行命令时,我得到了有效的结果:

php -v 2> /dev/null | awk '{print $2; exit}'
7.0.14

可能是什么问题?


As to possible reasons, why you can run the command from CLI, but not Ansible, most likely the path to the php executable is not defined in the PATH variable when you run shell through a non-interactive SSH session* (as Ansible does).

使用完整路径而不仅仅是php in the shell模块参数。


可能是什么问题?

当您在 shell 调用中使用管道时,返回代码将是最后一个命令的返回代码(awk),尽管第一个失败,但您不会收到通知。

awk 没有获得任何输入来处理,它会正常退出,因为您将 stderr 重定向到/dev/null你没有看到任何错误php命令。

例如,如果您显式运行一个不存在的命令:

- name: Check PHP version
    shell: qwerty -v 2> /dev/null | awk '{print $2; exit}'
    register: php_version

- debug: var=php_version

您还将得到:

"rc": 0,
"start": "2017-01-09 06:35:10.588258",
"stderr": "",
"stdout": "",
"stdout_lines": [],
"warnings": []

* See the Difference between Login Shell and Non-Login Shell? https://unix.stackexchange.com/questions/38175/difference-between-login-shell-and-non-login-shell question on Unix.SE.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Ansible:shell 脚本输出始终为空 的相关文章

随机推荐