How to beginner · 3 min read

Modal secrets explained

Quick answer
In Modal, secrets are securely stored environment variables or credentials managed via the modal.Secret class. You define secrets in the Modal dashboard or CLI, then inject them into your functions or containers without hardcoding, ensuring safe API key management.

PREREQUISITES

  • Python 3.8+
  • Modal account and CLI installed
  • Basic knowledge of environment variables
  • pip install modal

Setup

Install the modal Python package and configure your Modal CLI with your account. Define secrets in the Modal dashboard or via CLI to securely store API keys or credentials.

bash
pip install modal
modal login
output
Successfully logged in to Modal

Step by step

Create a modal.Secret object referencing your stored secret and mount it in your function or container. Access secrets as environment variables inside your Modal function without exposing them in code.

python
import os
import modal

# Reference a secret stored in Modal dashboard or CLI
my_secret = modal.Secret("my_api_key")

app = modal.App()

@modal.function(secret=my_secret)
def main():
    api_key = os.environ.get("MY_API_KEY")
    print(f"Using API key: {api_key[:4]}****")

if __name__ == "__main__":
    with app.run():
        main()
output
Using API key: abcd****

Common variations

You can inject multiple secrets by passing a list to the secret parameter. For async functions, use @modal.async_function(secret=...). Secrets can also be mounted as files inside containers using secret.mount().

python
import modal

# Multiple secrets
secret1 = modal.Secret("api_key_1")
secret2 = modal.Secret("api_key_2")

app = modal.App()

@modal.function(secret=[secret1, secret2])
def main():
    import os
    print("API_KEY_1:" , os.environ.get("API_KEY_1"))
    print("API_KEY_2:" , os.environ.get("API_KEY_2"))

if __name__ == "__main__":
    with app.run():
        main()
output
API_KEY_1: sk-xxxx
API_KEY_2: sk-yyyy

Troubleshooting

  • If your secret is not found, verify it is correctly created in the Modal dashboard or CLI.
  • Ensure the secret name matches exactly when creating modal.Secret.
  • Check that your function or container has the secret parameter set to inject the secret.
  • Use print(os.environ) inside your Modal function to debug environment variables.

Key Takeaways

  • Use modal.Secret to securely manage API keys without hardcoding.
  • Inject secrets into Modal functions via the secret parameter for safe access.
  • Define secrets in the Modal dashboard or CLI before referencing them in code.
  • Multiple secrets can be injected simultaneously as a list.
  • Debug missing secrets by verifying names and injection in your Modal app.
Verified 2026-04
Verify ↗