5

The issue we are facing is around environment variables. The JAVA_HOME is set to 1.5 for a user A and for root it is set to 1.7. When I login manually & check the versions in both A & root, it reflects the same.

When I SSH through ansible as user A with sudo set to true (sudo_user=root), I expected the java version to be 1.7 but it came back as 1.5, which is the version of user A.

Any ideas why things behave differently between manual login & ansible login?

grizzthedj
  • 7,131
  • 16
  • 42
  • 62
Ashwin Sridhar
  • 125
  • 1
  • 14
  • How are you checking the environment variables? – ydaetskcoR Dec 18 '15 at 08:31
  • I use env command. Also checking the java -version gives me a different version and the one I set explicitly set for the user in its .bashrc. I tried setting in .bash_profile – Ashwin Sridhar Dec 21 '15 at 08:50
  • maybe it has to do something with the sudo env vars. See [here](http://stackoverflow.com/questions/8633461/how-to-keep-environment-variables-when-using-sudo) – user2599522 Dec 22 '15 at 12:33

2 Answers2

7

Depending on your system's config, when Ansible escalates its privileges via sudo, the environment will be 'sanitised' giving you a minimal set of env variables. Your /etc/sudoers file likely has the setting env_reset.

You have a few options.

In the sudoers files you could remove env_reset or you could add env_keep MY_VAR entries for each of the variables you wish to preserve.

Within Ansible you could explicitly set the environment variables you require. Doing that on a specific task looks like this:

- hosts: all
  tasks:
    - cmd: echo $MY_ENV
      become: true
      environment:
        MY_ENV: "foo"

You can read more about setting the environment for Ansible in the Setting the Environment section of their docs.

Without knowing anything else of your needs, I would strongly recommend setting the variable within your Ansible code and leaving the sudoers file alone unless you genuinely need those values being kept in the env outside of Ansible's context. This helps avoid an inconsistent sudo environment for users.

Tom Manterfield
  • 6,515
  • 6
  • 36
  • 52
0

There are two things that are important here:

  • How are you checking root's environment variable? sudo env does not give you the right environment variables for root.
  • How are you setting root's environment variables?

My best guess is you're not setting the environment variables correctly. See this answer for how environment variables are read and set it at the right place.

Community
  • 1
  • 1
Nigel
  • 1,695
  • 1
  • 13
  • 22