How to set an environment variable on Linux distro for a user using ansible playbook?

2,769 views
Skip to first unread message

Pratik Dhandharia

unread,
Oct 1, 2015, 5:58:46 PM10/1/15
to Ansible Project
Hi All,

I need to set some environment variable for all the user who is executing the ansible script. Currently I am doing something like this in the playbook:

- hosts: all
  task:

  - name: get path
    shell: which R
    register: r_path

  - name: create file in /etc/profile.d
    shell: touch /etc/profile.d/rpath.sh
    sudo: yes
    args:
      creates: /etc/profile.d/rpath.sh

  - name: create environment variable and paste in file
    shell: echo "export RHOME={{ r_path.stdout }}" > /etc/profile.d/rpath.sh

  - name: reload profile
    shell: source /etc/profile

When I run this playbook, it works fine on RHEL machine. But it fails on Ubuntu machine. The reason being, on ubuntu source command is not present.

So what I was wondering is, can this be done in a better way? Or is there a better way to reload the profile on ubuntu ?

Also another question: When we have a playbook with multiple task, does ansible execute all the task as if it were a single session? or Each new task is a separate session with the host?

The reason I am asking is because, in my ansible script, once I have set the environment variable, I would like to use that in the next task.

Thanks

Brian Coca

unread,
Oct 1, 2015, 7:18:39 PM10/1/15
to Ansible Project
source is not a command its a builtin in bash, ansible uses /bin/sh if
it is not a symlink to bash or bash is set to do strict sh you won't
have 'source', but you always have . which does the same thing.

that said

shell: source /etc/profile

is a noop, it does nothing as ansible will open a new shell and that
info won't be available in other tasks.


you can do this to set an environment var for all tasks in a play:

- hosts: all
environment:
RHOME: /path/to/r
tasks:
- ....



--
Brian Coca

Pratik Dhandharia

unread,
Oct 2, 2015, 10:52:52 AM10/2/15
to Ansible Project
Thanks for clarifying my understanding and suggesting a workaround.

It worked!

Ashish Srivastava

unread,
May 5, 2018, 2:50:28 AM5/5/18
to Ansible Project
Hi All,

I've a similar problem, but I want to load environment variable "ORACLE_HOME" based on the hostname since ORACLE_HOME is different for each server.
And, there are n number of hosts defined in inventory, which in turn assigned to groups like dev, sit, uat etc.

In my scenario, I'm passing env_name to playbook, which resolves hostnames and does the deployment on those servers. I don't want to keep separate playbook for each server due to different ORACLE_HOME.

I tried multiple ways to do it. But no luck.

Anyone aware, how it can be achieved?

Thanks,
Ashish Kumar
Reply all
Reply to author
Forward
0 new messages