Reputation: 133
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
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
Reputation: 1920
/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:
ansible remote_host -b -m shell -a '. /etc/profile && (env | grep -iP "proxy")'
. /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 forUpvotes: 0
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