0

I am working on a django project where I have to keep secrete information to python's os.environ.

by following below link http://barkas.com/2016/set-environment-variables-activating-virtualenv/ code is working fine in local system.

Now when I run getting secrete key

$/home/env/bin/python
>> import os
>> os.environ
environ({'SECRETE_KEY': '000000')

but while excuting same command with sudo getting different environ variables.

I need to get environ({'SECRETE_KEY': '000000') with using sudo /home/env/bin/python

Also tried with
How to use a python virtualenv with sudo?

but it didn't help me.

1 Answer 1

0

BASH Variables are scoped. This means they are only available to certain things and not shared system-wide.

When you instantiate a variable, it is available for the current shell (x="apple"). When you export, that variable is available in the current shell, and subsequent shells/functions (export x="apple"). If you close that shell/terminal, you lose that variable.

For this reason, common variables are added to user profiles so that they are loaded properly. This is typically done using export in ~/.bashrc or ~/.bash_profile.

Similar to how the variable is lost if you close your terminal, these variables are lost if you switch users.

If you want root to have access to a BASH variable, you have to declare the variable within the root shell. You can duplicate your (assumed) exports in your ~/.bashrc into the root user's /root/.bashrc file, and have that sourced properly.

You may be able to export/push all variables by looking at man sudo (look at -E), as I know it has a few options on whether to switch to the new user's directory and possibly share variables, but this isn't the approach I would take.

Instead, similar to how you'd share a web server directory (/srv/www/) by having a shared group own the file (www-data, g+rwx), and making sure only that group can read the file (o-rwx), we will create a shared file to source and secure against unauthorized users. So, you can add the following to each user's ~/.bashrc file that is in the group and you want to have access to the variable:

$ touch /srv/www/.bashrc_shared
$ chown www-data:www-data /srv/www/.bashrc_shared
$ chmod g+rwx /srv/www/.bashrc_shared
$ chmod o-rwx /srv/www/.bashrc_shared
$ vim /srv/www/.bashrc_shared

#!/bin/bash

export MY_SECRET_VAR="super_secret_var"

Now, ensure ~/.profile sources this file, or your ~/.bashrc which then sources this file, or run sudo with the -i flag:

cat ~/.profile 
# ~/.profile
#

[[ -f /srv/www/.bashrc_shared ]] && source /srv/www/.bashrc_shared

OR

sudo -i your_command # Source config files

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .