DanielGibbs
DanielGibbs

Reputation: 10190

Loading global environment variables in an Ansible task

I have several global environment variables set in /etc/environment on my target machine that I need to present when running some Ansible tasks. E.g.

MY_VAR=Some global variable

The value of these global variables are not known to Ansible so I can't use the environment functionality.

Example task:

- shell: echo MY_VAR is $MY_VAR
  register: my_var

- debug: msg={{ my_var.stdout }}

The output I get is MY_VAR is where I would like it to be MY_VAR is Some global variable. I understand that this is happening because non-interactive Bash shells (which Ansible uses) don't load the environment from /etc/environment, but is there a way to execute my command in the context of that environment?

Note: I don't actually want to retrieve the value of the environment variable (as shown above), I just want it to be present in the context that I execute the shell task in.

Upvotes: 1

Views: 1942

Answers (1)

Zlemini
Zlemini

Reputation: 4973

Remote environment variables are available via facts using the the ansible_env variable.

This prints out all variables of the user Ansible logs into a remote host with:

- debug: var=ansible_env

If global environment variables not available to the Ansible user, they can be sourced in a task before running your command:

- shell: . /etc/environment && commandhere

Upvotes: 1

Related Questions