Sub topic 16
Configuration and per-environment settings
This chapter assumes you can define a stack with S3 and Lambda constructs. It also assumes you know what an environment (an account and region pair) is and how cdk synth and cdk deploy work. The goal is to deploy the same code to dev and prod with different settings, without copying files or editing code before each deploy.
Why configuration needs a plan
A CDK app is a program, so you could branch on anything: environment variables, command-line flags, files, or hard-coded values. Without a rule, those branches spread through your constructs and the synthesized template stops being predictable. Two rules keep it manageable:
- Resolve all configuration at synthesis time, before any construct is created.
- Pass the result into stacks and constructs as typed props, so constructs never read the outside world themselves.
Synthesis runs on your machine or build server. Values that only exist at deploy time are tokens, covered in an earlier chapter. You cannot use a token in an if statement, so configuration must be plain values.
The three sources of configuration
| Source | Where it lives | Best for | Caveat |
|---|---|---|---|
| Typed config in code | A map or interface in your repository | Per-stage settings such as memory size, retention, account IDs | Changes need a commit and review, which is usually what you want |
| Context | `cdk.json`, `cdk.context.json`, or `-c key=value` | Selecting a stage, feature flags, cached lookups | Values from the command line are always strings |
| Environment variables | The shell or CI system | The account and region the CLI resolved (`CDK_DEFAULT_ACCOUNT`, `CDK_DEFAULT_REGION`) | Hidden inputs make synth results depend on the machine |
Never put secrets in any of these. Config values end up in the synthesized template and in version control. Store a secret in AWS Secrets Manager or Systems Manager Parameter Store and pass its name or ARN. The stack can then reference the secret and CloudFormation resolves it at deploy time.
Context in detail
Context is a key-value store attached to the construct tree. The CDK merges it from several places, with later sources overriding earlier ones:
- The
contextsection ofcdk.jsonin the project. cdk.context.jsonin the project.~/.cdk.jsonin your home directory.- The
--context(-c) option on the command line.
You read a value with node.tryGetContext(key). It returns undefined when the key is missing. Use it for the choice of stage, not for large structures.
cdk.context.json has a second purpose that surprises people. When a construct performs a lookup against your account, such as Vpc.fromLookup or HostedZone.fromLookup, the CDK caches the answer there. This keeps synthesis stable, because a new subnet in the account will not silently change your template. Commit this file. To refresh stale values, run cdk context --reset <key> or cdk context --clear.
Lookups need a concrete account and region. A stack created with env: {} (environment-agnostic) cannot use them, and synthesis fails with an error saying so.
A typed configuration example
This app defines one config per stage. The stage is chosen with -c stage=prod, defaults to dev through cdk.json, and fails early on an unknown value.
{
"app": "npx ts-node --prefer-ts-exts app.ts",
"context": {
"stage": "dev"
}
}import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as s3 from 'aws-cdk-lib/aws-s3';
import * as lambda from 'aws-cdk-lib/aws-lambda';
interface StageConfig {
readonly account: string;
readonly region: string;
readonly memorySize: number;
readonly retainData: boolean;
}
const stages: Record<string, StageConfig> = {
dev: {
account: '111111111111',
region: 'us-east-1',
memorySize: 128,
retainData: false,
},
prod: {
account: '222222222222',
region: 'eu-west-1',
memorySize: 512,
retainData: true,
},
};
interface AppStackProps extends cdk.StackProps {
readonly config: StageConfig;
}
class AppStack extends cdk.Stack {
constructor(scope: Construct, id: string, props: AppStackProps) {
super(scope, id, props);
const { config } = props;
const bucket = new s3.Bucket(this, 'UploadsBucket', {
versioned: true,
removalPolicy: config.retainData
? cdk.RemovalPolicy.RETAIN
: cdk.RemovalPolicy.DESTROY,
autoDeleteObjects: !config.retainData,
});
const fn = new lambda.Function(this, 'Processor', {
runtime: lambda.Runtime.NODEJS_20_X,
handler: 'index.handler',
code: lambda.Code.fromInline(
'exports.handler = async () => ({ statusCode: 200 });'
),
memorySize: config.memorySize,
environment: { BUCKET_NAME: bucket.bucketName },
});
bucket.grantRead(fn);
}
}
const app = new cdk.App();
const stage = String(app.node.tryGetContext('stage'));
const config = stages[stage];
if (!config) {
throw new Error(
`Unknown stage "${stage}". Expected one of: ${Object.keys(stages).join(', ')}`
);
}
new AppStack(app, `AppStack-${stage}`, {
env: { account: config.account, region: config.region },
config,
});Deploy each stage with:
cdk deploy -c stage=dev
cdk deploy -c stage=prodThree details in this example matter. The stack ID includes the stage, so the two deployments never collide if they ever share an account. The retainData flag drives both the removal policy and autoDeleteObjects, so a dev bucket can be destroyed cleanly while the prod bucket survives cdk destroy. The config prop is an ordinary interface, so the compiler catches a missing setting.
The same pattern in Python
Only the naming differs. Context is read with app.node.try_get_context("stage"), and the config can be a dictionary or a dataclass passed to the stack constructor as a keyword argument.
from aws_cdk import App, Environment
STAGES = {
"dev": {"account": "111111111111", "region": "us-east-1", "memory": 128},
"prod": {"account": "222222222222", "region": "eu-west-1", "memory": 512},
}
app = App()
stage = str(app.node.try_get_context("stage"))
if stage not in STAGES:
raise ValueError(f"Unknown stage {stage!r}; expected one of {sorted(STAGES)}")
cfg = STAGES[stage]
env = Environment(account=cfg["account"], region=cfg["region"])
print(f"Would create AppStack-{stage} in {env.region} with {cfg['memory']} MB")Common errors
undefinedbecomes the string "undefined". CallingString()on a missing context value, as the example does, produces a stage name that fails the lookup and triggers the error message. This is intended, but check forundefinedexplicitly if you want a clearer message.- Numbers and booleans arrive as strings.
-c retain=falsegives you the string"false", which is truthy. Parse it, or keep structured values in code. - Reading
CDK_DEFAULT_ACCOUNTin prod. Those variables reflect whichever credentials you have active. That is convenient for personal sandboxes. For shared environments, pin the account in code so a wrong profile fails instead of deploying to the wrong place. - Conditionals on tokens.
if (bucket.bucketName === 'x')is never meaningful at synthesis time. Branch on config values only. - Branching inside constructs. If a reusable construct reads
process.envor context itself, its output depends on where it runs. Take a prop instead.
Exercise
You run cdk deploy -c retain=false and your code does if (app.node.tryGetContext('retain')) { removalPolicy = RETAIN }. The bucket is retained anyway. Why, and how do you fix it?
Show answer
Context values passed with -c are strings, so "false" is a non-empty string and is truthy. Compare explicitly (=== 'true') or parse the value once. A better fix is to keep the setting as a boolean in the typed stage config and select the stage with a single context key.
Exercise
A stack uses Vpc.fromLookup and is created with no env property. What happens at synthesis, and what two things do you change?
Show answer
Synthesis fails because lookups require a concrete account and region. Give the stack an explicit env (account and region), and commit the generated cdk.context.json so later synths reuse the cached lookup result.