Ansible - accessing local environment variables

Ansible

Ansible Problem Overview


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?

Ansible Solutions


Solution 1 - Ansible

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.

Solution 2 - Ansible

Use ansible lookup:

- set_fact: env_var="{{ lookup('env','ENV_VAR') }}"

Solution 3 - Ansible

Those variables are in the management machine I suppose source machine in your case.

Check this: https://docs.ansible.com/ansible/devel/collections/ansible/builtin/env_lookup.html

Basically, if you just need to access existing variables, use the ‘env’ lookup plugin. For example, to access the value of the HOME environment variable on management machine:`

Now, if you need to access it in the remote machine you can just run your ansible script locally in the remote machine. Or you could just the ansible facts variables. If it's not in the ansible facts you can just run a shell command to get it.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionalexs333View Question on Stackoverflow
Solution 1 - AnsiblegrilixView Answer on Stackoverflow
Solution 2 - AnsibleQuyen Nguyen TuanView Answer on Stackoverflow
Solution 3 - AnsibleRicoView Answer on Stackoverflow