Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to permanently set environment variable?

Tags:

ansible

Host is Ubuntu 16.04

I'm trying to set environment variable for user, with:

- hosts: all
  remote_user: user1
  tasks:
  - name: Adding the path in the bashrc files
    lineinfile: dest=/home/user1/.bashrc line='export MY_VAR=TEST' insertafter='EOF' state=present

  - name: Source the bashrc file
    shell: . /home/user1/.bashrc 

  - debug: msg={{lookup('env','MY_VAR')}}

Unfortunately it outputs:

TASK [debug] *******************************************************************
ok: [xxxxx.xxx] => {
    "msg": ""
}

How can I export variable so next time I run some tasks on this machine I can use {{ lookup('env', 'MY_VAR') }} to get value of this variable?

like image 450
Marcin Doliwa Avatar asked Sep 28 '16 14:09

Marcin Doliwa


1 Answers

Because lookups happen locally, and because each task runs in it's own process, you need to do something a bit different.

- hosts: all
  remote_user: user1
  tasks:
  - name: Adding the path in the bashrc files
    lineinfile: dest=/home/user1/.bashrc line='export MY_VAR=TEST' insertafter='EOF' state=present

  - shell: . /home/user1/.bashrc && echo $MY_VAR
    args:
      executable: /bin/bash
    register: myvar

  - debug: var=myvar.stdout

In this example I am sourcing the .bashrc and checking the var in the same command, and storing the value with register

like image 55
MillerGeek Avatar answered Nov 09 '22 05:11

MillerGeek