Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible - accessing local environment variables

Tags:

ansible

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?

like image 518
alexs333 Avatar asked Jan 29 '14 04:01

alexs333


People also ask

What plug in should be used in Ansible to get access to environment variables?

You can access the environment variables on the local server using the lookup plugin. It lets you access the system data and environment variables.

How do you access the environment variables of target remote host in Ansible?

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.

How do you pass multiple vars in Ansible?

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.

What does Set_fact do in Ansible?

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.


2 Answers

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.

like image 148
grilix Avatar answered Sep 29 '22 09:09

grilix


Use ansible lookup:

- set_fact: env_var="{{ lookup('env','ENV_VAR') }}" 
like image 21
Quyen Nguyen Tuan Avatar answered Sep 29 '22 10:09

Quyen Nguyen Tuan