8

I have $MY_VAR set to some value on the remote host, and I want to query it from a playbook (put it's value in an ansible variable), here's what I am seeing :

 - name: put shell var into ansible var command: echo $MY_VAR register: my_var - debug: var=my_var 
 ok: [192.168.78.10] => { "my_var": { "changed": true, "cmd": [ "echo", "$my_var" ], "delta": "0:00:00.002284", "end": "2014-12-17 18:10:01.097217", "invocation": { "module_args": "echo $my_var", "module_name": "command" }, "rc": 0, "start": "2014-12-17 18:10:01.094933", "stderr": "", "stdout": "$my_var", "stdout_lines": [ "$my_var" ] } } 

note:

If I change the command to :

 command: pwd 

then I get the expected result :

"my_var": { "stdout": "/home/vagrant", "stdout_lines": [ "/home/vagrant" ] } 

It seems as if echo does not expand when called from ansible

2
  • Are you sure, this environment variable is accessible anytime you ssh to the remote host? If you ssh to the machine, does doing "echo $MY_VAR" print something? I mean env variables could be set per terminal instance, so is it possible that your env variable is set on one terminal, but if you start a new tab it might not be visible? Commented Dec 17, 2014 at 18:43
  • echo $MY_VAR on the remote host prints the expected value, it is set in the ~/.profile of the user Commented Dec 17, 2014 at 18:50

2 Answers 2

8

The problem is that you are using the command module. Here's what the documentation says:

The given command will be executed on all selected nodes. It will not be processed through the shell, so variables like $HOME and operations like "<", ">", "|", and "&" will not work (use the shell module if you need these features).

So, use shell instead of command.

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

3 Comments

Doesn't lookup run locally? "These plugins are evaluated on the Ansible control machine"
Its also worth noting that environment variables may not be loaded at all - Ansible doesn't connect with an interactive session, so .bash_profile for example will not be parsed when Ansible connects to the server, and any configuration on the remote server held in there will be ignored...
@keba I agree, the whole thing is a big red flag. It seems like flagrant abuse of Ansible and configuration management.
2

Here's a way to do what you want to do, but without echo. Note you have to use braces to de-reference the variable.

- name: put shell var into ansible var set_fact: my_var: "{{ lookup('env','MY_VAR') }}" - name: print var debug: msg: var={{ my_var }} 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.