Forums

Trouble setting Django SECRET_KEY in environment variable

I'm attempting to assign sensitive data to environment variables. I have followed the article as posted here:

https://help.pythonanywhere.com/pages/environment-variables-for-web-apps/

Yet the key/value pairs that are declared in the .env file aren't poulating as environment variables. When I deactivate and activate the virtualenv, Bash raises an error with regards to a paranthesis found in the secret key: bash: /home/binnybit/django_stackoverflow/.env: line 2: syntax error near unexpected token (

How can this error be resolved with respect to the random secret keys generated by Django which may conflict with Bash syntax?

(myvirtualenv) 02:57 ~ $ cat django_stackoverflow/.env
SECRET_KEY=*v#$%j7vkat%(&a+4*w67=miel-5yr%&q8s#k-b4+*o#jdsm8l

(myvirtualenv) 03:03 ~ $ echo 'set -a; source ~/django_stackoverflow/.env; set +a' >> 
~/.virtualenvs/myvirtualenv/bin/postactivate
(myvirtualenv) 03:03 ~ $ echo $SECRET_KEY
(myvirtualenv) 03:04 ~ $ deactivate
03:04 ~ $ workon myvirtualenv
bash: /home/binnybit/django_stackoverflow/.env: line 2: syntax error near unexpected token `('
'ash: /home/binnybit/django_stackoverflow/.env: line 2: `SECRET_KEY=*v#$%j7vkat%(&a+4*w67=miel- 
5yr%&q8s#k-b4+*o#jdsm8l

It looks like bash is getting confused about some of the characters in your secret key. If you wrap the value in single quotes eg SECRET_KEY='the_key' then bash wont try to do anything clever with the value

I noticed that if I nested single quotes in Bash that it would not raise an error, but the single quotes would be appended to the value within the .env file:

echo "SECRET_KEY='......................'"

As I check for the environment variable in Python:

>>> import os
>>> "SECRET_KEY" in os.environ
True
>>> os.environ['SECRET_KEY']
'*v#$%j7vkat%(&a+4*w67=miel-5yr%&q8s#k-b4+*o#jdsm8l'

The variable appears to be stored in Bash as well:

(myvirtualenv) 18:32 ~/django_stackoverflow (main)$ echo $SECRET_KEY
*v#$%j7vkat%(&a+4*w67=miel-5yr%&q8s#k-b4+*o#jdsm8l

You may edit .env file directly in the editor if you do not want to fight with bash quoting and escaping.