Bash – How to Keep All Environment Variables for Specific Command in sudo

bashenvironment-variablessudo

I have a script that sets several environment variables and then finally calls another script using sudo.

The script run with sudo must be able to pick up those variables, and I'm not always going to be certain what those variables are.

Is there a way of configuring this sudoers entry to allow the command complete access to the callers env vars?

%deploy ALL=NOPASSWD: /bin/build.sh

When I run the sudo command from my script:

sudo -E build.sh "$@"

I get:

sudo: sorry, you are not allowed to preserve the environment

Googling around I've only found ways to preserve specific variables and not just everything.

Best Answer

After testing the first answer and still getting sudo: sorry, you are not allowed to preserve the environment, I decided to look around for a better solution.

After a bit of testing, I found that the option that matters is setenv.

Defaults!/bin/build.sh setenv

To make it a little more secure, we can add a couple settings:

Defaults    secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/X11/bin"
Defaults!/bin/build.sh setenv,env_reset,env_delete+=PATH,env_delete+=LD_PRELOAD,env_delete+=LD_LIBRARY_PATH,env_delete+=SSH_AUTH_SOCK,env_delete+=PYTHONPATH,env_delete+=PERL5LIB
%deploy  ALL=(ALL) NOPASSWD: /bin/build.sh *