Guide · AWS App Runner · Secrets Management · MCP Server
App Runner Secrets Management for MCP Servers — Secrets Manager, Parameter Store, and Rotation
MCP servers typically need API keys, database passwords, signing secrets, and third-party service credentials. Storing these as plain environment variables in an App Runner service definition exposes them in the AWS Console and in CloudTrail API logs. AWS App Runner supports injecting secrets from Secrets Manager and Systems Manager Parameter Store directly as environment variables at container startup — the secret value is resolved by App Runner before the container starts and injected as an environment variable, but it is never stored in plaintext in the service configuration. This guide covers both injection approaches, automatic rotation, and runtime secret access patterns.
TL;DR
Use RuntimeEnvironmentSecrets in the App Runner image configuration to reference Secrets Manager ARNs or SSM Parameter ARNs. App Runner resolves the secret at service deployment time and injects the value as an environment variable. For automatic rotation (database passwords, API keys), store secrets in Secrets Manager with a rotation Lambda and redeploy the App Runner service after each rotation. For high-frequency rotation (every hour), read secrets directly from Secrets Manager at runtime using the SDK instead of environment variable injection — this avoids the redeploy requirement.
Two approaches: injection vs runtime retrieval
App Runner supports two patterns for consuming secrets in your MCP server:
| Pattern | How it works | Pros | Cons |
|---|---|---|---|
| Environment injection | Secret ARN in RuntimeEnvironmentSecrets; App Runner resolves at deploy time and injects as env var |
No SDK calls in app code; works with any language; secret not visible in service config | Stale after rotation until redeployment; App Runner service must be redeployed to pick up rotated value |
| Runtime retrieval | Call GetSecretValueCommand from app code; cache with TTL |
Always gets latest version; works with rotation without redeployment; can refresh mid-flight | Extra SDK dependency and latency; requires IAM permission on instance role; cache invalidation logic |
Use environment injection for secrets that change rarely (OAuth client secrets, signing keys, static API keys). Use runtime retrieval for secrets that rotate automatically (RDS passwords, short-lived tokens, secrets with rotation policies).
Environment injection: Secrets Manager ARN
# Create a secret in Secrets Manager
aws secretsmanager create-secret \
--name mcp/database-url \
--description "PostgreSQL connection URL for MCP server" \
--secret-string "postgresql://user:pass@host:5432/dbname" \
--region us-east-1
# Note the ARN: arn:aws:secretsmanager:us-east-1:ACCOUNT:secret:mcp/database-url-AbCdEf
# Reference the ARN in App Runner service config (RuntimeEnvironmentSecrets)
aws apprunner update-service \
--service-arn arn:aws:apprunner:us-east-1:ACCOUNT:service/my-mcp-server/SERVICE_ID \
--source-configuration '{
"ImageRepository": {
"ImageIdentifier": "ACCOUNT.dkr.ecr.us-east-1.amazonaws.com/my-mcp-server:latest",
"ImageConfiguration": {
"Port": "8080",
"RuntimeEnvironmentVariables": {
"NODE_ENV": "production"
},
"RuntimeEnvironmentSecrets": {
"DATABASE_URL": "arn:aws:secretsmanager:us-east-1:ACCOUNT:secret:mcp/database-url-AbCdEf",
"STRIPE_SECRET_KEY": "arn:aws:secretsmanager:us-east-1:ACCOUNT:secret:mcp/stripe-key-XyZwVu",
"JWT_SIGNING_SECRET": "arn:aws:ssm:us-east-1:ACCOUNT:parameter/mcp/jwt-secret"
}
},
"ImageRepositoryType": "ECR"
}
}'
App Runner resolves the secret value when it starts the container. The resolved value is injected as the environment variable named in RuntimeEnvironmentSecrets (e.g., DATABASE_URL). Your Node.js code reads it with process.env.DATABASE_URL — no Secrets Manager SDK required.
To reference a specific version of a secret (not AWSCURRENT), append the version ID or staging label to the ARN: arn:...secret:mcp/database-url-AbCdEf:AWSPREVIOUS.
IAM permissions for secret injection
App Runner resolves RuntimeEnvironmentSecrets using the service's instance role. The instance role must have read permissions for all referenced secrets:
# Add to the instance role policy (AppRunnerMCPInstanceRole)
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"secretsmanager:GetSecretValue"
],
"Resource": [
"arn:aws:secretsmanager:us-east-1:ACCOUNT:secret:mcp/*"
]
},
{
"Effect": "Allow",
"Action": [
"ssm:GetParameters",
"ssm:GetParameter"
],
"Resource": [
"arn:aws:ssm:us-east-1:ACCOUNT:parameter/mcp/*"
]
},
{
"Effect": "Allow",
"Action": [
"kms:Decrypt"
],
"Resource": [
"arn:aws:kms:us-east-1:ACCOUNT:key/KEY_ID"
],
"Condition": {
"StringEquals": {
"kms:ViaService": "secretsmanager.us-east-1.amazonaws.com"
}
}
}
]
}
The KMS Decrypt permission is only needed if the secret is encrypted with a customer-managed key (CMK). Secrets encrypted with the default AWS-managed Secrets Manager key (aws/secretsmanager) do not need an explicit KMS permission.
Runtime retrieval with caching
For secrets that rotate (e.g., RDS passwords rotated every 30 days), read them from Secrets Manager at runtime and cache with a TTL shorter than the rotation interval:
import {
SecretsManagerClient,
GetSecretValueCommand,
} from "@aws-sdk/client-secrets-manager";
const smClient = new SecretsManagerClient({ region: process.env.AWS_REGION! });
interface CachedSecret {
value: string;
fetchedAt: number;
}
const secretCache = new Map<string, CachedSecret>();
const CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes
export async function getSecret(secretArn: string): Promise<string> {
const cached = secretCache.get(secretArn);
if (cached && Date.now() - cached.fetchedAt < CACHE_TTL_MS) {
return cached.value;
}
const command = new GetSecretValueCommand({ SecretId: secretArn });
const response = await smClient.send(command);
const value = response.SecretString ?? "";
secretCache.set(secretArn, { value, fetchedAt: Date.now() });
return value;
}
// Usage in an MCP tool handler:
server.tool("query_database", "...", { sql: z.string() }, async ({ sql }) => {
// Fresh-enough secret, never stale for more than 5 minutes
const dbUrl = await getSecret("arn:aws:secretsmanager:us-east-1:ACCOUNT:secret:mcp/database-url-AbCdEf");
const pool = getPool(dbUrl);
const result = await pool.query(sql);
return { content: [{ type: "text", text: JSON.stringify(result.rows) }] };
});
Set the cache TTL to less than the rotation interval and significantly less than the overlap window (the time Secrets Manager keeps the previous version available after rotation). For 30-day rotation with a 1-hour overlap window, a 5-minute TTL is safe and reduces Secrets Manager API calls substantially.
Automatic rotation with Secrets Manager
Secrets Manager can rotate secrets automatically using a Lambda function. For RDS database passwords, there are pre-built rotation templates:
# Enable automatic rotation for a database password secret
# Using the AWS-provided rotation template for RDS (single user)
aws secretsmanager rotate-secret \
--secret-id mcp/database-url \
--rotation-rules AutomaticallyAfterDays=30 \
--rotate-immediately
# Check rotation status
aws secretsmanager describe-secret \
--secret-id mcp/database-url \
--query 'RotationEnabled,LastRotatedDate,NextRotationDate'
When Secrets Manager rotates a secret, it:
- Creates a new version of the secret with the new value (staging label
AWSPENDING) - Updates the actual credential in the target service (e.g., changes the RDS user password)
- Tests the new credential
- Moves the staging label from
AWSPENDINGtoAWSCURRENT - Keeps the old value available as
AWSPREVIOUSduring the overlap window
If your MCP server uses environment injection, the injected value is not updated after rotation — you must redeploy the App Runner service to pick up the new value. Trigger a redeployment from an EventBridge rule that fires when Secrets Manager completes rotation:
# EventBridge rule to auto-redeploy App Runner on secret rotation
aws events put-rule \
--name mcp-secret-rotation-redeploy \
--event-pattern '{
"source": ["aws.secretsmanager"],
"detail-type": ["AWS API Call via CloudTrail"],
"detail": {
"eventName": ["RotateSecret"],
"requestParameters": {
"secretId": ["mcp/database-url"]
}
}
}'
# Lambda target to call apprunner:StartDeployment
# (create a small Lambda that calls the App Runner API)
For simpler setups, use runtime retrieval with caching — the new secret value is picked up within one cache TTL cycle after rotation, without any infrastructure automation.
SSM Parameter Store: simple and cheap
AWS Systems Manager Parameter Store is a good alternative to Secrets Manager for non-rotating secrets (API keys, feature flags, config values). SecureString parameters are encrypted with KMS and cost $0.05/parameter/month (vs ~$0.40/secret/month for Secrets Manager). There is no automatic rotation.
# Create a SecureString parameter
aws ssm put-parameter \
--name /mcp/openai-api-key \
--value "sk-..." \
--type SecureString \
--region us-east-1
# Reference in App Runner RuntimeEnvironmentSecrets (same as Secrets Manager)
# "OPENAI_API_KEY": "arn:aws:ssm:us-east-1:ACCOUNT:parameter/mcp/openai-api-key"
# Or reference by name (not ARN) — App Runner resolves by name:
# "OPENAI_API_KEY": "/mcp/openai-api-key"
For MCP servers with many configuration values (10+ parameters), use SSM Parameter Store with a path prefix (/mcp/prod/) and load all parameters at startup using GetParametersByPath. This is cheaper than Secrets Manager and simpler than managing individual secret ARNs.
Secret naming conventions
Establish a consistent naming convention for secrets to make IAM policies simple and avoid accidental permission sprawl:
# Recommended pattern:
# /app/environment/purpose
# or for Secrets Manager ARN-based access:
# app/environment/purpose
# Examples:
mcp/prod/database-url # PostgreSQL connection string
mcp/prod/stripe-secret-key # Stripe API secret key
mcp/prod/jwt-signing-secret # JWT signing key
mcp/prod/openai-api-key # OpenAI API key
mcp/prod/slack-webhook-url # Slack incoming webhook
# IAM policy using wildcard on the prefix — grants access to all prod secrets:
"Resource": "arn:aws:secretsmanager:us-east-1:ACCOUNT:secret:mcp/prod/*"
# Separate staging secrets from prod (different prefix → different IAM policy):
mcp/staging/database-url
mcp/staging/stripe-secret-key
Common errors and fixes
| Error | Cause | Fix |
|---|---|---|
Service deployment fails with AccessDeniedException | Instance role missing secretsmanager:GetSecretValue or ssm:GetParameter for the ARN | Add the missing permission to the instance role; ensure the ARN in RuntimeEnvironmentSecrets exactly matches the secret ARN |
| Environment variable is empty string | Secret exists but is empty; or ARN points to a JSON object (use a JSON key path) | Check secret value in console; for JSON secrets, use secretArn:jsonKey syntax (Secrets Manager supports JSON key access) |
| Stale database password after rotation | Using environment injection; App Runner did not redeploy after rotation | Switch to runtime retrieval with caching, or trigger App Runner redeploy after rotation via EventBridge → Lambda |
ResourceNotFoundException in runtime retrieval | Secret ARN is wrong or secret is in a different region | Verify ARN with aws secretsmanager describe-secret --secret-id ARN; ensure AWS_REGION in the client matches the secret region |
| High Secrets Manager API costs | Calling GetSecretValue on every request with no caching | Add in-process cache with 5-minute TTL; use Secrets Manager caching client library |