我正在尝试将Linux shell的输出插入变量,但是由于某种原因,该变量始终为空.
I'm trying to insert an output of Linux shell to a variable, but for some reason, the variable always empty.
这是Ansible代码:
Here is the Ansible code:
- 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": [] } }当我直接在服务器上运行命令时,我得到一个有效的结果:
When i run the command directly on the server, i get a valid result:
php -v 2> /dev/null | awk '{print $2; exit}' 7.0.14可能是什么问题?
推荐答案关于可能的原因,为什么可以从CLI运行命令,但不能从Ansible运行,很可能是 php 可执行文件的路径通过非交互式SSH会话运行shell时, PATH 变量中未定义 * (就像Ansible一样).
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).
在 shell 模块参数中使用完整路径,而不只是使用 php .
Use a full path instead of just php in the shell module argument.
可能是什么问题?
What could be the issue?
在shell调用中使用管道时,返回代码将是最后一个命令的返回代码( awk ),尽管第一个命令失败,但不会通知您.
As you are using a pipeline in the shell call, the return code will be that of the last command (awk) and although the first one fails, you won't be notified.
Awk没有任何输入要处理,它会正常退出,并且由于您将stderr重定向到/dev/null ,因此您不会在 php 命令.
Awk does not get any input to process and it quits gracefully, and because you are redirecting stderr to /dev/null you don't see any error from the php command.
例如,如果您明确运行不存在的命令:
For example if you explicitly run a non-existent command:
- 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": []* 参见区别在Unix.SE上是登录Shell和非登录Shell之间的问题?
* See the Difference between Login Shell and Non-Login Shell? question on Unix.SE.
更多推荐
Ansible:shell脚本输出始终为空
发布评论