Ansible:shell脚本输出始终为空

编程入门 行业动态 更新时间:2024-10-11 05:20:20
本文介绍了Ansible:shell脚本输出始终为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试将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脚本输出始终为空

本文发布于:2023-10-28 00:00:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1534913.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:为空   脚本   Ansible   shell

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!