Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I detect Heroku's environment?

I have a Django webapp, and I'd like to check if it's running on the Heroku stack (for conditional enabling of debugging, etc.) Is there any simple way to do this? An environment variable, perhaps?

I know I can probably also do it the other way around - that is, have it detect if it's running on a developer machine, but that just doesn't "sound right".

like image 929
aviraldg Avatar asked Feb 21 '12 18:02

aviraldg


People also ask

What is setting environment variables?

An environment variable is a variable whose value is set outside the program, typically through functionality built into the operating system or microservice. An environment variable is made up of a name/value pair, and any number may be created and available for reference at a point in time.

Are Heroku environment variables secure?

IMO both – environment variables and config files – are secure as long you can trust everyone that has access to your servers and you carefully reviewed the source code of all libraries and gems you have bundled with your app.

Does Heroku read .env file?

env file on Heroku isn't a good approach. Instead, you can use its built-in support for environment variables, using heroku config:set <var> <value> or its web UI. Either way, you'll get a regular environment variable. But for testing these config vars in local, we need to set up a .


2 Answers

An ENV var seems to the most obvious way of doing this. Either look for an ENV var that you know exists, or set your own:

on_heroku = False if 'YOUR_ENV_VAR' in os.environ:   on_heroku = True 

more at: http://devcenter.heroku.com/articles/config-vars

like image 153
Neil Middleton Avatar answered Sep 22 '22 22:09

Neil Middleton


Similar to what Neil suggested, I would do the following:

debug = True
if 'SOME_ENV_VAR' in os.environ:
    debug = False

I've seen some people use if 'PORT' in os.environ: But the unfortunate thing is that the PORT variable is present when you run foreman start locally, so there is no way to distinguish between local testing with foreman and deployment on Heroku.

I'd also recommend using one of the env vars that:

  1. Heroku has out of the box (rather than setting and checking for your own)
  2. is unlikely to be found in your local environment

At the date of posting, Heroku has the following environ variables:

['PATH', 'PS1', 'COLUMNS', 'TERM', 'PORT', 'LINES', 'LANG', 'SHLVL', 'LIBRARY_PATH', 'PWD', 'LD_LIBRARY_PATH', 'PYTHONPATH', 'DYNO', 'PYTHONHASHSEED', 'PYTHONUNBUFFERED', 'PYTHONHOME', 'HOME', '_']

I generally go with if 'DYNO' in os.environ:, because it seems to be the most Heroku specific (who else would use the term dyno, right?).

And I also prefer to format it like an if-else statement because it's more explicit:

if 'DYNO' in os.environ:
    debug = False
else:
    debug = True
like image 20
Ryan Shea Avatar answered Sep 26 '22 22:09

Ryan Shea