Gleeb Gleeb - 1 year ago 603
Linux Question

How to set linux environment variables with ansible

Hi i am trying to find out how to set environment variable with Ansible.

something that a simple shell command like this:


tried as shell command and got an error
tried using the environment module and nothing happend.

what am i missing

Answer Source

There are multiple ways to do this and from your question it's nor clear what you need.

1. If you need environment variable to be defined PER TASK ONLY, you do this:

- hosts: dev
    - name: Echo my_env_var
      shell: "echo $MY_ENV_VARIABLE"
        MY_ENV_VARIABLE: whatever_value

    - name: Echo my_env_var again
      shell: "echo $MY_ENV_VARIABLE"

Note that MY_ENV_VARIABLE is available ONLY for the first task, environment does not set it permanently on your system.

TASK: [Echo my_env_var] ******************************************************* 
changed: [] => {"changed": true, "cmd": "echo $MY_ENV_VARIABLE", ... "stdout": "whatever_value"}

TASK: [Echo my_env_var again] ************************************************* 
changed: [] => {"changed": true, "cmd": "echo $MY_ENV_VARIABLE", ... "stdout": ""}

Hopefully soon using environment will also be possible on play level, not only task level as above. There's currently a pull request open for this feature on Ansible's GitHub:

UPDATE: It's now merged as of Jan 2, 2015.

2. If you want permanent environment variable + system wide / only for certain user

You should look into how you do it in your Linux distribution / shell, there are multiple places for that. For example in Ubuntu you define that in files like for example:

  • ~/.profile
  • /etc/environment
  • /etc/profile.d directory
  • ...

You will find Ubuntu docs about it here:

After all for setting environment variable in ex. Ubuntu you can just use lineinfile module from Ansible and add desired line to certain file. Consult your OS docs to know where to add it to make it permanent.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download