What to do with passwords and secrets?

Hernán Tylim
Django Musings
Published in
2 min readApr 18, 2016

What should we do with all the secret stuff that we have in our code?

Meaning, Django’s SECRET_KEY setting, various user and password credentials (EMAIL, DATABASE, …), API KEYs to 3rd party REST API, so on…

Option one. We could just hardcode it in our code. Yes. That’s terrible.

For starters if you keep it in your code then it goes into your Code Repository. Now you are sharing your secret stuff with everybody else in your project. And if you don’t have team members it doesn’t matter. This secret stuff is now being backed up and stored and became vulnerable to theft or other stuff.

Option two. Keep it in the code, but avoid committing it with the rest of the files.

Depends on how you do it. If you keep a separate .py file with ONLY these settings, and use the multiple setting files pattern (next article) and avoid committing this file with the creds. Then ok. It might work.

So you only need to remember to avoid ever committing it by mistake.

option three. keep them in environment variables. This is my favorite. I took it from Two Scoops From Django. In the book they do it like these.

In your settings file you add:

import os
from django.core.exceptions import ImproperlyConfigured
def get_env_variable(name):
“””Gets the environment variable or throws ImproperlyConfigured
exception
:rtype: object
“””
try:
return os.environ[name]
except KeyError:
raise ImproperlyConfigured(
‘Environment variable “%s” not found.’ % name)

And now every time you need a parameter that you want out of your code you do this:

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = get_env_variable('SECRET_KEY')

And that’s it.

Of course for this to work you have to have a shell file (.sh, .bat, .cmd, whatever) that will initialize your environment with the proper values.

But that’s not biggie. Every IDE and deployment environment provides you a way to customize your app’s environment variables.

--

--