Defining Infrastructure with the AWS CDK
The AWS Cloud Development Kit (AWS CDK) defines cloud infrastructure in general-purpose programming languages, such as TypeScript, Python, Java, C# and Go, and synthesises it into CloudFormation templates. This lesson explains constructs and their levels, the app, stage and stack structure, synthesis and bootstrapping, the CDK CLI, aspects and testing, and CDK Pipelines for self-updating multi-account delivery.
Learning outcomes
After completing this lesson, you will be able to:
- Explain the CDK application model of apps, stages, stacks and constructs, including construct levels L1, L2 and L3.
- Describe synthesis, the cloud assembly and the resources created by bootstrapping.
- Explain how aspects, cdk-nag and assertion tests apply governance and quality checks to CDK code.
- Describe how CDK Pipelines deploys stages and waves across accounts and updates itself.
Why Use a Programming Language
CloudFormation templates are declarative but repetitive: creating twenty similar queues or encoding a standard pattern for every service requires copying YAML. The CDK lets engineers use loops, conditions, functions, classes and package managers to generate infrastructure, and it supplies higher-level abstractions with secure defaults. The output is still CloudFormation, so deployments keep CloudFormation's change sets, rollback and drift detection. CDK v2 ships as a single library, aws-cdk-lib, plus the constructs package.
Constructs and Their Levels
Everything in a CDK application is a construct, a class that represents one or more cloud resources. Constructs form a tree: each construct has a scope (its parent) and an ID that is unique within the scope, and the path through the tree determines logical IDs in the generated template. AWS constructs come in three levels.
- L1 (CFN resources)
- Generated directly from the CloudFormation specification, named with a
Cfnprefix, such asCfnBucket. Every property must be set explicitly. They give complete control and are available as soon as CloudFormation supports a resource. - L2 (curated constructs)
- Higher-level classes, such as
s3.Bucket, with sensible defaults, helper methods and grants.bucket.grantRead(role)generates a least-privilege policy, andqueue.metricApproximateNumberOfMessagesVisible()creates a metric for alarms. - L3 (patterns)
- Combinations of resources for a common architecture, such as
ecs_patterns.ApplicationLoadBalancedFargateService, which creates a cluster, a task definition, a service and a load balancer in a few lines.
Organisations write their own constructs to encode standards, such as a SecureBucket that always enables encryption, versioning and logging, and publish them as libraries in a package repository such as AWS CodeArtifact. Application teams then reuse the standards through normal dependency management. When an L2 construct does not expose a property, escape hatches such as node.defaultChild and addPropertyOverride modify the underlying L1 resource.
Which construct level?
Apps, Stages and Stacks
An app is the root of the construct tree. It contains stacks, each of which becomes one CloudFormation stack deployed to an environment, meaning an account and Region. A stage groups stacks that are deployed together, such as all stacks of a service, so that the same stage class can be instantiated for test and production with different environments and properties. References between stacks in the same environment are converted into CloudFormation exports and imports automatically, which brings the coupling described in the CloudFormation module.
from aws_cdk import App, Environment, Stage, Stack, Duration, aws_sqs as sqs, aws_lambda as lambda_
from constructs import Construct
class OrdersStack(Stack):
def __init__(self, scope: Construct, id: str, *, retention_days: int, **kwargs):
super().__init__(scope, id, **kwargs)
queue = sqs.Queue(self, "Orders", retention_period=Duration.days(retention_days))
handler = lambda_.Function(self, "Processor", runtime=lambda_.Runtime.PYTHON_3_12,
handler="app.handler", code=lambda_.Code.from_asset("src"))
queue.grant_consume_messages(handler) # least-privilege policy generated by the L2 construct
class OrdersStage(Stage):
def __init__(self, scope, id, *, retention_days, **kwargs):
super().__init__(scope, id, **kwargs)
OrdersStack(self, "Orders", retention_days=retention_days)
app = App()
OrdersStage(app, "Test", env=Environment(account="222222222222", region="eu-west-1"), retention_days=1)
OrdersStage(app, "Prod", env=Environment(account="333333333333", region="eu-west-1"), retention_days=14)
app.synth()Synthesis and Bootstrapping
cdk synth runs the program and produces a cloud assembly in cdk.out: CloudFormation templates for each stack plus assets, such as Lambda code directories and Docker images, that must be uploaded before deployment. Synthesis is deterministic only if the program does not depend on changing external state; values looked up from an account, such as an existing VPC found with Vpc.from_lookup, are cached in cdk.context.json, which should be committed so that synthesis gives the same result in the pipeline.
Before CDK can deploy to an environment, the environment must be bootstrapped with cdk bootstrap. Bootstrapping deploys a CloudFormation stack named CDKToolkit containing an S3 bucket for file assets, an ECR repository for image assets and IAM roles: a deployment role used to start deployments, file and image publishing roles used to upload assets, a lookup role for context lookups and a CloudFormation execution role that CloudFormation uses to create resources. For cross-account pipelines, the target environment is bootstrapped with --trust <pipeline-account> so that the pipeline account can assume these roles, and --cloudformation-execution-policies restricts what the execution role may create, which should be narrower than the default AdministratorAccess in production. Organisations commonly bootstrap every account and Region with a StackSet.
The following diagram shows what synthesis produces and what bootstrapping creates.

The CDK CLI
The main CLI commands are listed below.
cdk synth: produce the cloud assembly.cdk diff: compare the synthesised templates with deployed stacks, showing resource and IAM changes, similar to a change set preview.cdk deploy: publish assets and deploy stacks through CloudFormation change sets, prompting for approval of security-relevant changes unless--require-approval neveris set.cdk deploy --hotswapandcdk watch: update Lambda code and some other resources directly for fast development iterations, deliberately introducing drift; never for production.cdk destroy: delete stacks.cdk bootstrap: prepare environments, as described above.
Aspects, cdk-nag and Testing
An aspect is a visitor that CDK applies to every construct in a scope during synthesis. Aspects can inspect constructs and add errors or warnings, or modify them, which makes them a tool for governance: an aspect can fail synthesis if any bucket lacks encryption or add mandatory tags to every resource. cdk-nag is an open-source set of aspects, maintained by AWS, that checks a CDK application against rule packs such as AWS Solutions, HIPAA and NIST 800-53, and reports or fails on findings, with suppressions that require a documented reason.
Because CDK code is code, it can be unit tested. The assertions module synthesises a stack and checks the template, for example that a bucket has a specific property (Template.from_stack(stack).has_resource_properties(...)) or that a resource count is expected. Snapshot tests compare the whole template with a stored version to detect unintended changes. These tests run in the build stage before anything is deployed.
CDK Pipelines
CDK Pipelines is a construct library that defines a CodePipeline pipeline for deploying CDK applications. The pipeline is defined in the same CDK app as the application. Its synth step, usually a ShellStep that installs dependencies, runs tests and runs cdk synth, produces the cloud assembly. A self-mutation stage then updates the pipeline itself if its definition changed, so that adding a stage or account in code changes the pipeline on the next commit. Asset publishing stages upload assets, and each added stage deploys its stacks with change sets.
Stages can be grouped in waves that deploy in parallel, such as several Regions of production, and each stage or wave can have pre and post steps: a ManualApprovalStep for sign-off, or a ShellStep that runs integration tests against stack outputs passed as environment variables. CDK Pipelines relies on the target accounts being bootstrapped with trust for the pipeline account.
The comparison below summarises when to use each IaC tool covered so far.
The following diagram shows the stages of a CDK pipeline.

CDK delivery
A Multi-Account CDK Delivery
A team builds a containerised service with the CDK and must deploy it to a test account and to production in two Regions, with integration tests after test and approval before production.
-
Bootstrap
Bootstrap the test and production accounts in each Region with --trust for the tooling account and a restricted execution policy.
-
Pipeline
Define a CDK pipeline in the tooling account whose synth step runs unit tests, cdk-nag and cdk synth.
-
Test stage
Add the service stage for the test account with a post ShellStep that runs integration tests against the load balancer URL output.
-
Production wave
Add a wave with two production stages, one per Region, and a ManualApprovalStep as the wave's pre step.
A CDK deployment to a new account fails with an error that the bootstrap stack or its roles cannot be found. What must be done?
Show answer
Bootstrap the account and Region with cdk bootstrap, using --trust for the pipeline account if a cross-account pipeline deploys to it.
Exam Tips
Remember for the exam
- L1 constructs map one-to-one to CloudFormation resources; L2 constructs add defaults and grant methods; L3 patterns combine resources.
- cdk bootstrap creates the CDKToolkit stack (asset bucket, ECR repository, deploy, publishing, lookup and execution roles); use --trust for cross-account pipelines.
- Commit cdk.context.json so lookups are deterministic; use cdk diff to preview changes.
- Aspects and cdk-nag enforce standards across all constructs at synthesis; assertions test templates.
- CDK Pipelines self-mutates, publishes assets and deploys stages and waves with pre and post steps such as ManualApprovalStep and ShellStep.
- hotswap and cdk watch are for development only because they bypass CloudFormation.