Sub topic 15
Configuration and per-environment settings
This chapter assumes you can define stacks and set env on them, as covered in the earlier chapters on environments and resources. It shows how to run one CDK app against several environments, such as dev and prod, without copying code.
Why configuration belongs in code
A prod stack usually differs from a dev stack in a few values: the account, the region, versioning, retention, and instance sizes. The construct code should stay the same. Only the inputs should change.
Because a CDK app is ordinary code, you can pass those inputs as typed values. A typo then fails at compile time instead of at deploy time.
A typed configuration per stage
Define an interface for the settings and a table that maps a stage name to its values. Pass the chosen values to the stack through its props.
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as s3 from 'aws-cdk-lib/aws-s3';
interface StageConfig {
account: string;
region: string;
versioned: boolean;
retain: boolean;
}
const stages: Record<string, StageConfig> = {
dev: { account: '111111111111', region: 'us-east-1', versioned: false, retain: false },
prod: { account: '222222222222', region: 'eu-west-1', versioned: true, retain: true },
};
interface AppStackProps extends cdk.StackProps {
config: StageConfig;
}
class AppStack extends cdk.Stack {
constructor(scope: Construct, id: string, props: AppStackProps) {
super(scope, id, props);
const { config } = props;
new s3.Bucket(this, 'UploadsBucket', {
versioned: config.versioned,
removalPolicy: config.retain ? cdk.RemovalPolicy.RETAIN : cdk.RemovalPolicy.DESTROY,
autoDeleteObjects: !config.retain,
});
}
}
const app = new cdk.App();
const stage: string = app.node.tryGetContext('stage') ?? 'dev';
const config = stages[stage];
if (!config) {
throw new Error(`Unknown stage "${stage}". Use one of: ${Object.keys(stages).join(', ')}`);
}
new AppStack(app, `AppStack-${stage}`, {
env: { account: config.account, region: config.region },
config,
});The stack ID includes the stage. This gives each environment its own CloudFormation stack and its own entry in cdk.out.
Choosing the stage with context
Context is a set of key-value pairs the app reads through node.tryGetContext. You can set a value in three places:
- On the command line:
cdk deploy -c stage=prod. - In the
contextsection ofcdk.json, for a default such as"stage": "dev". - In
cdk.context.json, which the CDK writes itself.
The command line wins over cdk.json. Values passed with -c are always strings, so convert them yourself if you need a number or a boolean.
cdk diff -c stage=prod
cdk deploy -c stage=prodPitfalls
- Keep
cdk.context.jsonin version control. It caches the results of lookups such asVpc.fromLookup, so every synth gives the same template. Without it, a later synth can pick up different values. - Do not read secrets into the config table. Store a secret's name or ARN in the config, and let the resources fetch the value at deploy or run time.
- Lookups need a concrete account and region. If
envis left unset, the stack is environment-agnostic and lookups fail. - Avoid branching on
process.envall through the construct code. Read it once at the top of the app and pass plain values down.
Choosing where a setting lives
| Setting | Good place |
|---|---|
| Values that differ per stage | Typed config table |
| Which stage to build | Context, `-c stage=...` |
| Cached lookup results | `cdk.context.json` |
| Secret values | Secrets Manager or SSM, referenced by name |
Exercise
You run cdk deploy with no -c flag, and the app above deploys to the dev account. Where does the dev value come from, and what would you add so the same command targets prod by default in CI?
Show answer
The ?? fallback in app.node.tryGetContext('stage') ?? 'dev' supplies dev when no context value exists. To target prod in CI, pass -c stage=prod in the pipeline command, or set "stage": "prod" in the context section of cdk.json for that checkout. The command-line flag takes precedence over cdk.json.