Using environment variables in a devcontainer#

Hardcoded variables are never a good idea and one solution is the update the during deployment with Ansible for example. Another option is to set read those variables from the environment and maintaining them via systemd via a separate environment file or as part of the container deployment.

The example below is how Django reads the environment variables to configure the database connection to Postgresql. This way the application can easily be configured as is described in Environment variables set by systemd and the application itself never has to be modified or redeployed.

A snippet from settings.py for the database connection#
DATABASES = {
  "default": {
    "ENGINE": "django.db.backends.postgresql",
    "NAME": os.environ.get("DB_DATABASE", "postgres"),
    "USER": os.environ.get("DB_USERNAME", "postgres"),
    "PASSWORD": os.environ.get("DB_PASSWORD", "postgres"),
    "HOST": os.environ.get("DB_HOSTNAME", "postgres"),
    "PORT": "5432",
  },
}

How do we set these variables safely in a devcontainer during development? One of the options is to define them as remote environment variables in devcontainer.json as shown below. After restarting the devcontainer the command printenv will show that these variables are set.

Setting environment variables via .devcontainer/devcontainer.json#
{
    //...
    "remoteEnv": {
        "DB_USERNAME": "postgres",
        "DB_PASSWORD": "postgres",
        "DB_DATABASE": "postgres",
        "DB_HOSTNAME": "db"
    }
}

Other options do exist and may depend on the framework that is being used, but setting the environment variables for development via devcontainer.json is a safe way to do so and follows the Infrastructure-as-Code principles. No extra steps and the whole environment if configured when starting the devcontainer.