Home:ALL Converter>Ansible - Update env variables during playbook execution

Ansible - Update env variables during playbook execution

Ask Time:2017-09-14T21:28:21         Author:PyTzatzi

Json Formatter

I want to update an environment variable on the host (this playbook is executed locally) during the ansible playbook execution, so the remaining tasks can use the updated value of the env variable but it seems that this is not possible.

Let me give you an example of what I am trying to accomplish:

# Environment variable before changing
- set_fact: env_before="{{ lookup('env', 'ENV_VAR') }}"

# A task that updates the env variable, I tried to make the needed configuration
# into ~/.bashrc, ~/.bash_profile, ~/.profile, /etc/environment

# Environment variable after changing
- set_fact: env_after="{{ lookup('env', 'ENV_VAR') }}"

# Unfortunately env_after = env_before

If I re-execute the playbook, but this time not changing the env variable, the env_before and env_after will have the updated value of the env variable.

Example:

- 1st Execution:
 - env_before = ENV_VAR = 10
 - update_ENV_VAR to 20 and update ~/.bashrc, ~/.bash_profile, ~/.profile, /etc/environment files
   with export ENV_VAR=20 etc.
 - env_after = ENV_VAR = 20

- 2nd Execution (Do not make any changes just skip the update_ENV_var step
 - env_before = ENV_VAR = 20 (new value from previous execution)

So as of my understanding, ansible is loading env variables only on the start of the playbook, and keeps these values until the end. And it seems that the ansible tasks are not updating/sourcing the corresponding bash conf file. So I cannot find a way to update an ENV variable which its new value will be available in the following task.

The only way this may work is to define environment: keyword in the next task, but I want to avoid this. This new value will be used by many tasks, so I'm searching a way to update its value once during playbook execution.

Author:PyTzatzi,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/46220468/ansible-update-env-variables-during-playbook-execution
yy