Lesson 24 of 30Infrastructure as code
AWS CDK in Depth
The construct tree and logical IDs, bootstrap and the CLI, grants, context, cross-stack exports, stateful resources, testing, cdk-nag and pipelines.
A teammate tidies the CDK code by moving the orders table into a new Data construct. The code compiles, the tests pass, and cdk diff shows [-] AWS::DynamoDB::GlobalTable OrdersA9B65338 destroy and [+] AWS::DynamoDB::GlobalTable DataOrders20A4E13F. A harmless refactor has become "create an empty table and delete the one with all the orders in it". You met CDK in Deploying a Full-Stack App as a fast way to describe a stack. This lesson is what you need to run it for years: how the construct tree turns into CloudFormation, which refactors are dangerous, how cross-stack references lock you in, and how to test and police the result.
The construct tree
Everything in CDK is a construct: an object with a parent (its scope) and an id unique among its siblings. Together they form a tree.
- App is the root. It runs your program and writes the output.
- Stage groups stacks that deploy together to one environment, such as
DevorProd. - Stack becomes one CloudFormation stack.
- Constructs inside stacks become resources.
Constructs come in three levels:
- L1 constructs are generated from the CloudFormation spec and named
Cfn*(CfnBucket,CfnFunction). One L1 is exactly one CloudFormation resource with exactly its properties. No defaults, no helpers. - L2 constructs (
s3.Bucket,lambda.Function,dynamodb.TableV2) wrap one L1 with sensible defaults and methods likegrantRead. Most of your code uses these. - L3 constructs, or patterns, create many resources for a use case, like
ApplicationLoadBalancedFargateService.
The App is the root. A Stage called Prod groups the stacks for one environment.
Logical IDs: why a refactor can replace a database
CloudFormation identifies a resource inside a stack by its logical ID. Change the logical ID and CloudFormation sees one resource removed and a new one added: it creates the new resource and deletes the old one. CDK computes logical IDs from the construct path inside the stack. This is the real algorithm in miniature (it matches what cdk synth produces):
Press Run (⌘ Enter) to see what happens.The readable part drops Resource, but the 8-character hash covers the full path. So renaming an id, or wrapping a construct in a new parent, changes the logical ID. Moving a construct to another stack is the same: it leaves one stack and appears in another.
What does this print?
import hashlib
def h(path):
return hashlib.md5(path.encode()).hexdigest()[:8].upper()
print(h("Orders/Resource") == h("Data/Orders/Resource"))How to refactor without losing data:
- Read
cdk diffbefore every deploy and treatdestroyorreplaceon a stateful resource as a stop sign. - Pin the ID with
(table.node.defaultChild as dynamodb.CfnGlobalTable).overrideLogicalId("OrdersA9B65338")when you must move a construct. cdk refactor(in preview, behind--unstable=refactorat the time of writing) uses CloudFormation stack refactoring to move resources to new logical IDs or between stacks without replacement. Check the docs for its current status.- Write a test that asserts the logical IDs of stateful resources never change (shown below).
Escape hatches
When an L2 does not expose what you need, drop to the L1 underneath. node.defaultChild returns it.
const bucket = new s3.Bucket(this, "Assets", {
enforceSSL: true,
versioned: true,
removalPolicy: RemovalPolicy.RETAIN,
});
const cfnBucket = bucket.node.defaultChild as s3.CfnBucket;
cfnBucket.addPropertyOverride("Tags", [{ Key: "data-class", Value: "public" }]);
cfnBucket.overrideLogicalId("AssetsBucket");addPropertyOverride writes any raw CloudFormation property, even one CDK has never heard of, and is applied after synthesis. overrideLogicalId fixes the ID, which is also how you adopt a resource from an older hand-written template without replacing it. Use escape hatches sparingly and comment why; each one is a place where CDK's defaults no longer protect you.
The workflow and the CLI
npx cdk bootstrap aws://123456789012/eu-west-2npx cdk synthnpx cdk diffnpx cdk deploy "Dev/*"npx cdk watchcdk bootstrap deploys a stack called CDKToolkit into each account and Region once. It holds an S3 bucket for file assets (zipped Lambda code), an ECR repository for Docker image assets, an SSM parameter recording the bootstrap version, and IAM roles: a deploy role the CLI assumes, file and image publishing roles, a read-only lookup role, and the CloudFormation execution role that actually creates your resources. To let a pipeline account deploy into prod, you bootstrap prod with --trust <pipeline-account>. The error SSM parameter /cdk-bootstrap/hnb659fds/version not found means the target was never bootstrapped. Enable termination protection on that stack; deleting it breaks every deploy.
cdk synth runs your program and writes the cloud assembly to cdk.out: one template per stack, asset manifests, and the construct tree. Nothing touches AWS except context lookups. cdk diff compares templates with the deployed stacks. cdk deploy uploads assets with the publishing roles, then creates and executes a change set.
--hotswap skips CloudFormation and updates Lambda code, ECS images or state machine definitions directly through service APIs. It takes seconds instead of minutes, which is why cdk watch uses it, but the stack no longer matches the template: deliberate drift. Use it only in a personal dev stack, never in shared or production environments.
Since early 2025 the CLI (aws-cdk, versions 2.1000.0 and up) and the library (aws-cdk-lib, still 2.x) are released separately. The CLI supports library versions released before it, so keep the CLI at least as new as the library, ideally as a pinned dev dependency run with npx. Newer commands worth knowing: cdk drift to detect drift, cdk gc to clean old assets out of the bootstrap bucket and repository, and cdk import and cdk migrate to adopt existing resources.
cdk deploy --hotswap in the production pipeline because it cuts deploy time from 6 minutes to 20 seconds. Why is that a bad idea?Grants and connections
Grants are the best reason to use CDK on AWS. One method call writes a least-privilege IAM policy scoped to the exact resource.
interface ApiStackProps extends StackProps {
table: dynamodb.ITableV2;
}
export class ApiStack extends Stack {
constructor(scope: Construct, id: string, props: ApiStackProps) {
super(scope, id, props);
const fn = new lambda.Function(this, "CreateOrder", {
runtime: lambda.Runtime.NODEJS_24_X,
handler: "index.handler",
code: lambda.Code.fromAsset("lambda"),
timeout: Duration.seconds(10),
environment: { TABLE_NAME: props.table.tableName },
});
props.table.grantReadWriteData(fn);
}
}grantReadWriteData adds GetItem, Query, PutItem, UpdateItem, DeleteItem, BatchWriteItem and related data actions on that table's ARN (and its indexes) to the function's role. It does not grant DeleteTable or any control-plane action. Prefer the narrowest grant: grantReadData for a reader, grantWriteData for a writer. For network access, connections does the same job for security groups: db.connections.allowDefaultPortFrom(service) writes the ingress rule referencing the service's security group, as you saw in Deploying a Full-Stack App.
Environments and context
A stack with no env is environment-agnostic: one template that works anywhere, but CDK cannot look anything up and Stack.of(this).region is an unresolved token. Give stacks an explicit env whenever they look things up or must deploy to a specific account.
Lookups like ec2.Vpc.fromLookup(this, "Vpc", { tags: { Name: "shop-prod" } }) query your account at synth time through the lookup role and cache the answer in cdk.context.json. Commit that file. Without it, CI performs the lookup again, and if someone added a subnet in the meantime the template changes on a commit that touched no infrastructure. To refresh a value deliberately, run cdk context --reset <key> and review the diff.
Stages are how you deploy the same app to several environments:
export class ShopStage extends Stage {
constructor(scope: Construct, id: string, props?: StageProps) {
super(scope, id, props);
const data = new DataStack(this, "Data");
new ApiStack(this, "Api", { table: data.table });
}
}
const app = new App();
new ShopStage(app, "Dev", { env: { account: "111111111111", region: "eu-west-2" } });
new ShopStage(app, "Prod", { env: { account: "222222222222", region: "eu-west-2" } });Cross-stack references and the export lock
Passing data.table into ApiStack crosses a stack boundary. CDK handles it by adding a CloudFormation Output with an Export to Prod-Data and an Fn::ImportValue in Prod-Api. It works invisibly until you try to stop using it.
CloudFormation refuses to delete or change an export while any stack imports it. Remove the reference in code, deploy, and the producer's update fails with Export Prod-Data:ExportsOutputFnGetAttOrders... cannot be deleted as it is in use by Prod-Api. The same lock blocks replacing the table, because a replacement changes the exported ARN.
You deleted the code that passes the table to the API. CDK deploys the producer first, because the consumer depends on it.
Many teams avoid the lock entirely for values that change or cross team boundaries: the producer writes the table name to an SSM parameter, and the consumer reads it with ssm.StringParameter.valueForStringParameter(this, "/shop/orders-table-name"). You lose CDK's automatic ordering and type safety, and you gain stacks that deploy independently. Keep direct references for tightly coupled stacks in one app; use parameters between independently owned ones.
You want Prod-Api to stop using the table exported by Prod-Data. Order the steps that avoid the export lock.
- Tap the steps below in the right order.
Stateful resources
Decide on purpose what happens to data when a resource leaves the stack. removalPolicy maps to CloudFormation's DeletionPolicy and UpdateReplacePolicy:
RemovalPolicy.RETAINkeeps the resource, orphaned, when it is removed or replaced. L2 tables, buckets and log groups default to it.RemovalPolicy.SNAPSHOTtakes a final snapshot first, for RDS and EBS; database instances default to it.RemovalPolicy.DESTROYdeletes it. Fine for dev stacks; withautoDeleteObjects: truea bucket is emptied first.
Retain protects data, but it is not free of surprises: a retained table still exists, so a redeploy that tries to create a table with the same fixed name fails. That is one reason to let CDK generate physical names for stateful resources and pass them around, instead of hardcoding tableName. For production, also turn on pointInTimeRecoverySpecification for DynamoDB, deletion protection for RDS, and termination protection on the stack.
Testing with assertions
aws-cdk-lib/assertions loads a synthesized template and lets you check it in Jest or Vitest. Test what would hurt if it changed: retention, encryption, permissions and the logical IDs of stateful resources.
import { App } from "aws-cdk-lib";
import { Match, Template } from "aws-cdk-lib/assertions";
import { ApiStack, DataStack } from "../lib/shop";
test("orders table is retained", () => {
const template = Template.fromStack(new DataStack(new App(), "Data"));
template.hasResource("AWS::DynamoDB::GlobalTable", {
DeletionPolicy: "Retain",
UpdateReplacePolicy: "Retain",
});
});
test("the API can write orders", () => {
const app = new App();
const data = new DataStack(app, "Data");
const template = Template.fromStack(new ApiStack(app, "Api", { table: data.table }));
template.hasResourceProperties("AWS::IAM::Policy", {
PolicyDocument: {
Statement: Match.arrayWith([
Match.objectLike({ Action: Match.arrayWith(["dynamodb:PutItem"]), Effect: "Allow" }),
]),
},
});
});
test("the orders table keeps its logical ID", () => {
const template = Template.fromStack(new DataStack(new App(), "Data"));
expect(Object.keys(template.findResources("AWS::DynamoDB::GlobalTable"))).toEqual(["OrdersA9B65338"]);
});Snapshot tests (expect(template.toJSON()).toMatchSnapshot()) catch every change, which is both their strength and their weakness: asset hashes change whenever Lambda code changes, so people learn to update snapshots without reading them. Use fine-grained assertions for the rules that matter and snapshots, if at all, as a reviewer aid.
Aspects and cdk-nag
An Aspect visits every construct in a scope after your code runs, so it can enforce a rule across a whole app:
class RequireVersioning implements IAspect {
visit(node: IConstruct): void {
if (node instanceof s3.CfnBucket && !node.versioningConfiguration) {
Annotations.of(node).addError("S3 buckets must have versioning enabled");
}
}
}
Aspects.of(app).add(new RequireVersioning());An error annotation fails cdk synth, so the rule runs locally and in CI with no extra tooling. cdk-nag packages hundreds of such checks as rule packs (AWS Solutions, HIPAA, NIST 800-53, PCI DSS). Its current major, v3, plugs into CDK's validation API; older code and most tutorials use the v2 style with Aspects.of(app).add(new AwsSolutionsChecks()) and NagSuppressions.
Validations.of(app).addPlugins(new AwsSolutionsChecks(app));
Validations.of(bucket).acknowledge({
id: "AwsSolutions-S1",
reason: "Public assets; CloudFront logs cover access",
});Every acknowledgement needs a reason a reviewer can judge. A pull request that adds ten acknowledgements is a pull request to read carefully.
Pipelines
Two common ways to run CDK in CI:
- CDK Pipelines (
pipelines.CodePipeline) defines an AWS CodePipeline in the same app. It is self-mutating: the pipeline updates itself when you change its definition, then deploys each stage in waves, with manual approval steps between them. It suits AWS-centered teams with many accounts. - GitHub Actions (or any CI) running the CLI: synth once, then deploy that same cloud assembly to each stage with
npx cdk deploy --app cdk.out "Prod/*" --require-approval never. Deploying the synthesized assembly, instead of re-synthesizing per stage, guarantees prod gets exactly what staging tested.--require-approval neveris safe here only because the approval happens earlier, in a reviewed diff and an environment gate. CI/CD to AWS with GitHub Actions builds this pipeline end to end.
Match each need to the CDK feature that meets it.
- construct
- A node in the CDK tree with a scope and an id. Apps, stages, stacks and resources are all constructs.
- L1 / L2 / L3
- Raw
Cfn*resources, opinionated single-resource wrappers, and multi-resource patterns. - logical ID
- A resource's name inside a CloudFormation stack. CDK derives it from the construct path plus a hash.
- escape hatch
- Reaching the L1 under an L2 with
node.defaultChildto set raw properties or override the logical ID. - bootstrap stack
CDKToolkit: the asset bucket, ECR repository, version parameter and roles CDK needs in each account and Region.- export lock
- CloudFormation's refusal to delete or change an export while another stack imports it.
- Aspect
- A visitor applied to every construct in a scope after construction, used for policy checks and bulk changes.