I wonder if there is a way for Ansible to access local environment variables.
The documentation references accessing variable on the target machine:
{{ lookup('env', 'SOMEVAR') }}
Is there a way to access environment variables on the source machine?
You can access the environment variables on the local server using the lookup plugin. It lets you access the system data and environment variables.
We can use the ansible_env and lookup function to retrieve the environment variables stored. - name: Ansible playbook to get linux environment variables. The above playbook retrieves all the environment variables inside the unix os. Now we need to retrieve the USER env variable.
To pass a value to nodes, use the --extra-vars or -e option while running the Ansible playbook, as seen below. This ensures you avoid accidental running of the playbook against hardcoded hosts.
This module allows setting new variables. Variables are set on a host-by-host basis just like facts discovered by the setup module. These variables will be available to subsequent plays during an ansible-playbook run.
I have a Linux vm running on osx, and for me:
lookup('env', 'HOME')
returns "/Users/Gonzalo" (the HOME
variable from osx), while ansible_env.HOME
returns "/root" (the HOME
variable from the vm).
Worth to mention, that ansible_env.VAR
fails if the variable does not exists, while lookup('env', 'VAR')
does not fail.
Use ansible lookup
:
- set_fact: env_var="{{ lookup('env','ENV_VAR') }}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With