SUDO - Retain Root Environment Variable

Just a note to remind myself instead of searching on Google all the time

As always, when I tried to sudo a command that requires Root environment variable, the OS will tell me that environmental variable is not set. This is because sudo reset environment variable to prevent leakage of Root information due to security reason

If you have some environment variable such as

export XXX=/usr/local/XXX/

and if you perform a command require XXX environment variable

sudo xxx_cmd

you will have problem running it.

2 ways to solve this issue

Using sudo -E

You can use -E options in sudo to preserve environment variable. This will override env_reset option in sudoers.

sudo -E xxx_cmd

This is a quick one time command to execute a command that require Root environment variable

Modifying /etc/sudoers

sudoers file contains a list of rules on which users may execute what when sudo command is executed.

There is a whole list of things you can do with sudoers file, but, I will not be going through here. Please see http://www.sudo.ws/sudoers.man.html

If you take a look at /etc/sudoers, you will see a line

Defaults env_reset

This tell sudo to run in minimal environment and only keep any variables in the caller's environment that match the env_keep and env_check lists are then added.

So, to make things works, do the following

1. Open /etc/sudoers with any editors

2. Add the following to append XXX environment variable to env_keep

Defaults env_keep += "XXX"

3. Make sure your user environment variable contain XXX as well.

4. Execute sudo xx_cmd will work now

This solution provide a long term fix if your environment variable are used frequently.




Comments

Popular Posts