PyTzatzi
PyTzatzi

Reputation: 41

Ansible - Update env variables during playbook execution

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.

Upvotes: 4

Views: 6004

Answers (1)

larsks
larsks

Reputation: 311238

The only way to change the environment presented to tasks is to use the environment keyword on a task or on a play. If you are using shell: tasks you could explicitly source your ~/.bashrc, etc, but that isn't very pretty.

What if you split your playbook into multiple plays, and set the environment key on the play after you've derived its value? Something like this:

- hosts: localhost
  tasks:
    - set_fact:
        myvar: "some value"

- hosts: localhost
  environment:
    MYVAR: "{{ myvar }}"
  tasks:
    - shell: "echo $MYVAR"
      register: res

    - debug:
        msg: "MYVAR = {{ res.stdout }}"

This would modify the environment for all tasks in the second play.

Upvotes: 2

Related Questions