Environment variables and secrets

With PythonDeploy you can easily modify the behavior and configuration of you application using Environment Variables and Secrets.

The main differences between the two are that:

  • Environment Variables are visible from your Dashboard, while Secrets are masked by default (but their value can be revealed).
  • Environment Variables are visible from Lambda and ECS dashboards in AWS console, while Secrets are not.
  • Environment Variables can be read directly from os.environ while Secrets are retrieved using boto3.

You can add, edit and remove them using you application's dashboard.

Reading your environment variables

Use the following code examples to read the values of the environment variables that you have created through Python Deploy.

import os

DEBUG = os.environ.get("DEBUG_ENABLED") == "yes"

# Environment variables are always strings, it is good
# practice to give the default value also as a string.
CACHE_TIMEOUT = int(os.environ.get("CACHE_TIMEOUT", "3600"))

# If you have not set a value for `REQUIRED`, this will
# raise a `KeyError` exception.
os.environ["REQUIRED"]
1
2
3
4
5
6
7
8
9
10
11

Reading your secrets

Use the following example as a starting point to retrieve AWS secrets from your python application.

TIP

No AWS credentials are necessary, the environments automatically provide them to boto3.

import os

import boto3

def get_aws_secret(secret_arn):
    """Return the secret value from an AWS secret."""
    secrets_client = boto3.client("secretsmanager")
    secret = secrets_client.get_secret_value(SecretId=secret_arn)
    return secret["SecretString"]

# Get the URL of your default database.
DATABASE_URL = get_aws_secret(os.environ["DATABASE_URL_SECRET"])
1
2
3
4
5
6
7
8
9
10
11
12

You can check if an environment variable points to a secret, and retrieve it automatically, or return the raw value if it does not:

import os

import boto3

def get_environ_or_aws_secret(env_var):
    """
    Return the value of an environment variable or AWS secret.

    It checks an environment variable, and if its value points
    to an AWS secret, retrieve it and return it instead.
    """
    env_var_value = os.environ.get(env_var)
    if env_var_value and env_var_value[:23] == "arn:aws:secretsmanager:":
        # Use `get_aws_secret()` from previous example.
        return get_aws_secret(env_var_value)

    return env_var_value

# Get the URL of your default database.
DATABASE_URL = get_environ_or_aws_secret("DATABASE_URL_SECRET")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20