Prashanth_Ramanathan
Prashanth_Ramanathan

Reputation: 133

Ansible - Reading Environment Variable from Remote Host

I am trying to read an Environment variable from Target Linux Host using Ansible playbook. I tried all the below tasks as per the document but there is no result.

   - name: Test1    
     debug: msg="{{ ansible_env.BULK }}"
     delegate_to: "{{ target_host }}"

   - name: Test2  
     shell: echo $BULK
     delegate_to: "{{ target_host }}"
     register: foo

   - debug: msg="{{ foo.stdout }}"

   - name: Test3 
     debug: msg="{{ lookup('env','BULK')}} is an environment variable"
     delegate_to: "{{ target_host }}"

The Environment variable "BULK" is not set in the local Host where I am executing the playbook, so I assume its returning nothing. Instead of BULK, if I use "HOME" which is always available, it returns the result. If I SSH into the target_host I am able to run echo $BULK without any issue.

How to obtain the Environment variable from the remote host?

Upvotes: 5

Views: 5412

Answers (3)

der_abu
der_abu

Reputation: 61

Remote environment variables will be automatically gathered by ansible during the "Gathering Facts" task.

You can inspect them like this:

- name: inspect env vars
  debug:
    var: ansible_facts.env

In your case try this:

- name: Test4 
  debug: msg="{{ ansible_facts.env.BULK }} is the value of an environment variable"
  

Upvotes: 1

Oliver Gaida
Oliver Gaida

Reputation: 1920

source /etc/profile and then grep the env

my solution is not perfect, but often works. for example i want to check if the remote_host has environment variables for proxy servers, i do the following:

as an adhoc ansible command:

ansible remote_host -b -m shell -a '. /etc/profile && (env | grep -iP "proxy")'

Explanation:

  • i prefere the shell module, it does what i expect... the same if i do it on a shell
  • . /etc/profile sources the /etc/profile. And this file sources other files like under /etc/profile.d . So after this i have the fix machine part of the environment.
  • env | grep -iP "proxy" then filter the expanded environment for my variables i am looking for

Upvotes: 0

techraf
techraf

Reputation: 68459

If I SSH into the target_host I am able to run echo $BULK without any issue.

Most likely, because BULK is set in one of the rc-files sourced only in an interactive session of the shell on the target machine. And Ansible's gather_facts task runs in a non-interactive one.

How to obtain the Environment variable from the remote host?

Move the line setting the BULK variable to a place where it is sourced regardless of the session type (where exactly, depends on the target OS and shell)

See for example: https://unix.stackexchange.com/a/170499/133107 for hints.

Upvotes: 3

Related Questions