Secrets provide secure environment variable injection for your Modal Functions and Sandboxes.
Referencing secrets
FromName
References a Secret by its name.
secret, err := mc.Secrets.FromName(ctx, "my-secret", &modal.SecretFromNameParams{
RequiredKeys: []string{"API_KEY", "SECRET_TOKEN"},
})
if err != nil {
// Handle error
}
Context for the operation
Optional parametersEnvironment name. Defaults to client’s environment.
List of required environment variable keys. The operation will fail if any are missing.
Returns:
*Secret - The Secret instance
error - NotFoundError if the Secret doesn’t exist
FromMap
Creates an ephemeral Secret from a map of key-value pairs.
secret, err := mc.Secrets.FromMap(ctx, map[string]string{
"API_KEY": "abc123",
"SECRET_TOKEN": "xyz789",
}, nil)
if err != nil {
// Handle error
}
Context for the operation
keyValuePairs
map[string]string
required
Map of environment variable names to values
Returns:
*Secret - The ephemeral Secret instance
error - Error if creation fails
Secrets created with FromMap are ephemeral and will be cleaned up automatically.
Managing secrets
Delete
Deletes a named Secret.
err := mc.Secrets.Delete(ctx, "my-secret", &modal.SecretDeleteParams{
AllowMissing: false,
})
if err != nil {
// Handle error
}
Context for the operation
The name of the Secret to delete
Optional parametersIf true, don’t error if the Secret doesn’t exist
Returns:
error - Error if deletion fails
Deletion is irreversible and will affect any Apps currently using the Secret.
Secret type
The unique identifier for the Secret
The name of the Secret (empty for ephemeral Secrets)
Example usage
package main
import (
"context"
"fmt"
"io"
"github.com/modal-labs/modal-client/go"
)
func main() {
ctx := context.Background()
mc, _ := modal.NewClient()
defer mc.Close()
// Reference a named Secret
secret, err := mc.Secrets.FromName(ctx, "api-keys", &modal.SecretFromNameParams{
RequiredKeys: []string{"OPENAI_API_KEY"},
})
if err != nil {
panic(err)
}
// Create an ephemeral Secret
ephemeralSecret, _ := mc.Secrets.FromMap(ctx, map[string]string{
"DEBUG": "true",
"LOG_LEVEL": "info",
"API_TIMEOUT": "30",
}, nil)
// Use Secrets with a Sandbox
app, _ := mc.Apps.FromName(ctx, "my-app", &modal.AppFromNameParams{
CreateIfMissing: true,
})
image := mc.Images.FromRegistry("python:3.11", nil)
sb, _ := mc.Sandboxes.Create(ctx, app, image, &modal.SandboxCreateParams{
Secrets: []*modal.Secret{secret, ephemeralSecret},
})
defer sb.Terminate(ctx, nil)
// Verify the environment variables are set
p, _ := sb.Exec(ctx, []string{"sh", "-c", "echo $DEBUG"}, nil)
stdout, _ := io.ReadAll(p.Stdout)
fmt.Printf("DEBUG value: %s\n", stdout)
// Use Secrets with Sandbox.Exec
execSecret, _ := mc.Secrets.FromMap(ctx, map[string]string{
"TEMP_VAR": "temporary_value",
}, nil)
p2, _ := sb.Exec(ctx, []string{"sh", "-c", "echo $TEMP_VAR"}, &modal.SandboxExecParams{
Secrets: []*modal.Secret{execSecret},
})
stdout2, _ := io.ReadAll(p2.Stdout)
fmt.Printf("TEMP_VAR value: %s\n", stdout2)
}