Application configuration with environment variables¶
Environment variables are dynamic values that can be used by the processes orapplications running on the server. One of the advantages in using them is thatyou can isolate specific values from your codebase.
Environment variables are a good place for storing instance-specificconfiguration, such as Django settings that you don’t wish to hard-code intoyour project.
On Cloud sites, environment variables for a project are managed via the commandline, or via the Control Panel. The variables for the Live and Test sitesare wholly independent.
The Divio CLI allows you to set and check values fromthe command line with the command, as long as youare within the path of the local version of the project. For example, to seethe variables of the Live server:
If any exist, they will be displayed thus:
- Key Value
- ------------------- -------
See the reference formore.
In the project, select Environment Variables. Enter the keys and values, andSave.
By default these are:
Lines should not contain spaces or quotation marks (see Docker’s documentation).
As you can see from the local environment examples above, environment variablescan also be used to apply Django settings, such as DEBUG
.
To access the environment variable in your own Python code, you could usesomething like this:
- import os
- my_variable = os.environ.get('MY_ENVIRONMENT_VARIABLE')
It’s important to note that if your variable represents anything other than astring, you will need to interpret the variable appropriately, as will only return a string.
You can also use env()
(from the getenv
package), which will parse thevariable as Python code.
Environment variables should apply only to environments, and not to states or processes that areindependent of a particular environment.
- When a project is running, it runs in a particular environment, so you can expect environmentvariables to apply.
- When a project is being built (i.e. in the deployment phase), it should not be subject to anyparticular environment conditions. Even Django operations that take place during deployment (suchas collectstatic) should be environment-agnostic - under all environment conditions, youshould expect the same result from collectstatic.
For example:
- RUN SOMEVAR=some_value ./manage.py collectstatic
However, it’s usually better to find another solution.
Many of the applications packaged for Divio Cloud deployment recognise a numberof environment variables for your convenience.
See for lists of settings that can be provided as variablesin some Divio Cloud addons.
They do this in their Application configuration with aldryn_config.py files. To seeprecisely how they are handled, refer to the aldrynconfig.py
file of keyaddons (_important: make sure you are looking at the correct version of theaddon, as different versions of the packages will assume different variablesand settings):
Our uWSGI application gateway also that commence UWSGI_
.