Environment variables
Environment variables are system specified variables that depends on the host system. Software would read it from the system and adjust their behavior.
The variables are usually strings and names are UPPERCASED
.
Setting Environment Variables
Many systems has built-in way to set them, Some has dashboard to set them e.g. AWS ElasticBeanstalk, Vercel and Netlify. IntelliJ based IDEs also has a place to put them.
In Linux systems, they can be put into ~/.bashrc
-file.
export VARIABLE_NAME="value"
Development Setup
Use Docker and set them in .env
-file or directly in the configuration.
Production Setup
It is recommended to use .env
-files that are loaded to application.
A third-party package to load them might be needed, usually need to be performed only once
in the program start and shouldn't change until the program is restarted.
VARIABLE_NAME=value
Notice that quotation marks are not used!
An alternative to using dotenv, perhaps better in some cases is to load configuration from json
or yaml
.
Reading Environment Variables
Many programming languages have a way to read them e.g. in Python
import os
VARIABLE_NAME: str = os.environ['VARIABLE_NAME']
Never put default values, since it causes bugs. If you want default values for development environments, put them directly into Docker configurations.
Conversion to other data types
Since the values are always strings, we need to convert them to other types
import os
def to_bool(value: str) -> bool:
"""
Returns True if value is 'True'.
"""
return value == 'True'
DEBUG: bool = to_bool(os.environ['DEBUG'])
MAX_CONNECTIONS: int = int(os.environ['MAX_CONNECTIONS'])