herokuflaskenvironment-variablesgunicornforeman

flask/gunicorn: setting environment variable from environment variable


On python/flask/gunicorn/heroku stack, I need to set an environment variable based on the content of another env variable.

For background, I run a python/Flask app on heroku. I communicate with an addon via a environment variable that contains credentials and url. The library I use to communicate with the addon needs that data, but needs it in a different format. Also, it needs it as an environment variable.

So far, I had cloned and reformatted the environment variable manually, but that just brought disaster because the add-on provider was changing passwords.

OK, so I need to automate reading one environment variable and setting another, before the library starts looking for it.

The naive approach I tried was (file app.py):

app = Flask(__name__, ...)
env_in = os.environ['ADDON_ENV_VAR']
os.environ['LIB_ENV_VAR'] = some_processing(env_in)
...
if __name__ == '__main__':
    app.run(host='0.0.0.0', port='5000')

That works fine when doing python app.py for debugging, but it fails when running via gunicorn app:app -b '0.0.0.0:5000' (as a Procfilefor foreman) for deploying a real webserver. In the second case, the env var doesn't seem to make it to the OS level. I'm not sure about how wsgi works, but maybe the environment changes once gunicorn starts running the app.

What can I do to have the environment variable set at the place it's needed?


Solution

  • you could also set the enviroment variables at run time as such

    gunicorn -b 0.0.0.0:5000 -e env_var1=enviroment1 -e env_var2=environment2