Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 522
bebbi Avatar asked Sep 04 '25 17:09

bebbi


2 Answers

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
like image 182
Shankar ARUL Avatar answered Sep 07 '25 16:09

Shankar ARUL


OK, so the answer (via Kenneth R, Heroku) is to set the environment before running gunicorn. I.e. write a Procfile like

web: sh appstarter.sh

which calls a wrapper (shell, python, ..) that sets up the environment variable and then runs the gunicorn command, like for example

appstarter.sh:

export LIB_ENV_VAR=${ADDON_ENV_VAR}/some/additional_string
gunicorn app:app -b '0.0.0.0:5000'

Just in case it helps anyone else out there.

like image 42
bebbi Avatar answered Sep 07 '25 18:09

bebbi