问题
I'm trying to insert an output of Linux shell to a variable, but for some reason, the variable always empty.
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
And here is the output:
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
What could be the issue?
回答1:
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).
Use a full path instead of just php
in the shell
module argument.
What could be the issue?
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 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
you will also get:
"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? question on Unix.SE.
来源:https://stackoverflow.com/questions/41535189/ansible-shell-script-output-always-empty