Reputation: 12573
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?
Upvotes: 82
Views: 119264
Reputation: 1047
Use delegate_to
to run it on any machine you want:
- name: get running ansible user
ansible.builtin.set_fact:
local_ansible_user: "{{ lookup('env', 'USER') }}"
delegate_to: localhost
Upvotes: 2
Reputation: 61551
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.
Upvotes: 8
Reputation: 1675
Use ansible lookup
:
- set_fact: env_var="{{ lookup('env','ENV_VAR') }}"
Upvotes: 32
Reputation: 5341
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.
Upvotes: 121