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 the Lambda function page 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.

Reading your secrets

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

No AWS credentials are necessary, the Lambda environment automatically provides 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"])

You can have some fancy magic that will detect if an environment variable points to a secret, and retreieve 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 received the name of an environment variable, and if it
    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")

Something missing? → [email protected]