Reputation: 419
I am trying to set Environment Variables for a Nginx And Gunicorn Served Django Project on Ubuntu.
The variables are set for the Ubuntu user and i am able to see the value using printenv VAR_EMAIL
.
But when i use them django settings it is not working , using them as os.environ['VAR_EMAIL']
,This doesn't get the value of the variable in production and server doesn't work.
However this works on Development side.
UPDATE 1st May 2020:
I used systemd and passed the variable like this in gunicorn.service file.This won't work still get key error,)Will post the exact error) as it is production on Ubuntu but i am developing on Windows and it works fine with Environment Variables in Development.
is os.environ['var_name']
correct way to access that ?
I also tried os.environ.get('var_name')
as i saw in some video that environ have .get()
to access the value. I will try again maybe i made some mistake.Feel free to ask for any info required.
ANSWERED - It was error on my end.
Upvotes: 2
Views: 5128
Reputation: 419
Now after many problems i faced because of which i just hard coded the variables in code for long time the solution i reached is in this update.Read the complete answer to get it.
This is an update,it is odd how the environment variables are passed along.
Every variable require the following method but you also need to add the variables to the etc/environment
and add the Environment variables in it too.
The environment Variables were to be set in a single line with
spaces
separating each key+value pair. (Not like mentioned in selected Answer) Couldn't get it to work with supervisor though.
So the correct way to do it is as mentioned in this Documentation for Systemd : EnvironmentsSystemd
Environment = "KEY_NAME_1=VALUE_KEY_1" "KEY_NAME_2=VALUE_KEY_2" ....
Then User PassEnvironment
to activate those in that session.
This way with PassEnvironment you can have different Environment Variables active for Different Services.
PassEnvironment = KEY_NAME_1 KEY_NAME_2 ....
This is Key Names seperated by spaces. This should help you setup systemd . Check the Selected answer for all the links.
Upvotes: 2
Reputation: 161
What are you using to supervise and run the gunicorn process in Ubuntu? If you're not using any, I recommend you to use systemd
, there's a small guide on how to setup in the gunicorn docs: https://docs.gunicorn.org/en/stable/deploy.html#systemd
After that, you can set the environment variables in the systemd config file doing like the following, under the [Service]
section of the systemd config file:
[Service]
Environment="VAR_EMAIL=var-email"
Environment="ANOTHER_VAR=another-var"
You can also use the EnvironmentFile
directive if you prefer to have these variables in a separate file: https://www.freedesktop.org/software/systemd/man/systemd.exec.html#EnvironmentFile=
Upvotes: 4