Hassan Baig
Hassan Baig

Reputation: 15824

How to robustly set Django secret key as environment variable

My Django project's secret key contains special characters such as #, @, ^, * etc. I'm trying to set this as an env variable at /etc/environment.

I include the following in the file:

export SECRET_KEY='zotpbek!*t_abkrfdpo!*^@#plg6qt-x6(%dg)9p(qoj_r45y8'

I.e. I included single quotes around the string since it contains special characters (also prescribed by this SO post). I exit the file and do source /etc/environment. Next I type env in the terminal: SECRET__KEY correctly shows.

I log out and log back in. I type env again.

This time SECRET_KEY still shows, but is cut off beyond the @ character. It's excluding everything beyond (and including) the # character.

How do I fix this issue? Trying with double quotes didn't alleviate anything either. My OS is Ubuntu 14.04 LTS.


p.s. I'm aware environment variables don't support access control; there's a bunch of reasons not to set the Django secret key as an env var. For the purposes of this ques, let's put that on the back burner.

Upvotes: 2

Views: 3833

Answers (3)

khashashin
khashashin

Reputation: 1137

Easiest way is to generate one using python3 in you linux terminal with following inline script:

python3 -c 'import random; print("".join([random.choice("abcdefghijklmnopqrstuvwxyz0123456789!@%^&*-_") for i in range(50)]))'

this will generate secret key without unsafe characters

Upvotes: 1

shivansh
shivansh

Reputation: 530

As per the django-environ documention you can use unsafe characters in .env file.

https://django-environ.readthedocs.io/en/latest/index.html#tips

To use unsafe characters you have to encode with urllib.parse.encode before you set into .env file.

Example:- admin#123 = admin%28123

Upvotes: 0

Mark Chackerian
Mark Chackerian

Reputation: 23512

This isn't a Django problem per se. According to this question Escape hash mark (#) in /etc/environment you can't use a "#" in /etc/environment.

I would recommend that you keep regenerating your secret key until you get one without #s -- that should fix the problem. Django Extensions has a command generate_secret_key for this. The side effect of changing the secret key is that current sessions will become invalid, that is, unless you are using it other places in your application.

Upvotes: 1

Related Questions