Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git/Heroku - How to hide my SECRET_KEY?

Im using Python and Django to create a Heroku web app and Heroku gives me this error after the command 'git push heroku master': ModuleNotFoundError: No module named 'dlist.secret_settings' when attempting to do this:

#settings.py
from .secret_settings import *  
# from secret_settings.py import * doesn't work for some reason.

Here is what secret_settings.py (which is in the same folder as settings.py) contains:

#secret_settings.py
SECRET_KEY = 'string here'

The problem is, this works when I test my web app on my local server (ie http://127.0.0.1:8000/), but its not working when I push these changes to Heroku. All I want to do is hide my SECRET_KEY, per others advice, as you can see. Ive looked at others suggestions and I can't seem to figure it out, choosing this method because it was understandable. Very frustrating. Beginner friendly answers/steps are greatly appreciated.

like image 465
xv8 Avatar asked Dec 23 '17 01:12

xv8


1 Answers

I'm guessing you've configured Git to ignore secret_settings.py. That's the only reason I can think of to create a separate file.

Heroku deploys are powered by Git. Since secret_settings.py isn't tracked by Git it doesn't get pushed to Heroku. You could add the file to your repository, but that would defeat the purpose of having a separate untracked file in the first place.

The solution is to use an environment variable. This is well-supported on Heroku.

In your settings.py file, set your SECRET_KEY using os.getenv() like this:

import os

SECRET_KEY = os.getenv('SECRET_KEY', 'Optional default value')

This tells Django to load your SECRET_KEY setting from an environment variable called SECRET_KEY. If no such environment variable exists it will fall back to the optional default value. On your development machine it's probably fine to use the default.

Finally, set the SECRET_KEY environment variable on Heroku. You can do this by running heroku config:set SECRET_KEY="YOUR_SECRET_KEY_VALUE" on your development machine, or via Heroku's web-based dashboard.

Your secret_settings.py file is no longer required.

like image 176
Chris Avatar answered Oct 25 '22 19:10

Chris