4

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?

4
  • 1
    I can't reproduce this problem. I copied your plays and ran on both ansible 2.0.1.0 on macos and ansible 2.3.0 on ubuntu and I get stdout correctly on both. Commented Jan 8, 2017 at 18:02
  • I cannot reproduce either. When you run the command directly on the server, are you using the same user and shell /bin/sh that Ansible uses? Commented Jan 8, 2017 at 19:16
  • No. Ansible runs with a different user from a designated server. Commented Jan 8, 2017 at 20:08
  • Try running it without the 2> /dev/null | awk '{print $2; exit}', hopefully you should see the error. Commented Jan 8, 2017 at 22:20

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.