Secrets

Secrets provide a dictionary of environment variables for images.

Secrets are a secure way to add credentials and other sensitive information to the containers your functions run in. You can create and edit secrets on the dashboard, or programmatically from Python code.

Using secrets

To inject secrets into the container running your function, you add the secret= or secrets=[...] argument to your stub.function annotation. For deployed secrets (typically secrets defined on the Modal website) you can refer to your secrets using Secret.from_name(secret_name).

For example, if you have a secret called secret-keys containing the key MY_PASSWORD:

import os
import modal

stub = modal.Stub()


@stub.function(secret=modal.Secret.from_name("secret-keys"))
def some_function():
    secret_key = os.environ["MY_PASSWORD"]
    ...

Each secret can contain multiple keys and values but you can also inject multiple secrets, allowing you to separate secrets into smaller reusable units:

@stub.function(secrets=[
    modal.Secret.from_name("my-secret-name"),
    modal.Secret.from_name("other-secret"),
])
def other_function():
    ...

The secrets are applied in order, so key-values from later modal.Secret objects in the list will overwrite earlier key-values in the case of a clash. For example, if both modal.Secret objects above contained the key FOO, then the value from "other-secret" would always be present in os.environ["FOO"].

Programmatic creation of secrets

In addition to defining secrets on the modal web page, you can programmatically create a secret directly in your script and send it along to your function using Secret.from_dict(...). This can be useful if you want to send secrets from your local development machine to the remote Modal app.

import os
import modal

stub = modal.Stub()
stub["my_local_secret"] = modal.Secret.from_dict({"FOO": os.environ["LOCAL_FOO"]})


@stub.function(secret=stub["my_local_secret"])
def some_function():
    print(os.environ["FOO"])

You can also use Secret.from_dotenv() to load any secrets defined in an .env file:

@stub.function(secret=modal.Secret.from_dotenv())
def some_other_function():
    print(os.environ["USERNAME"])