AWS from Zero to Production — Phase 6, Part 3 of 5 · See the full series roadmap
Here’s a Fargate service behind an Application Load Balancer, in a new VPC, with logging, health checks, and IAM roles:
const vpc = new ec2.Vpc(this, 'Vpc', { maxAzs: 2 });
new ecsPatterns.ApplicationLoadBalancedFargateService(this, 'OrdersApi', {
vpc,
desiredCount: 2,
taskImageOptions: {
image: ecs.ContainerImage.fromRegistry('public.ecr.aws/nginx/nginx:latest'),
},
});
That’s it. Those few lines generate hundreds of lines of CloudFormation: subnets, route tables, NAT gateways, security groups, roles, a cluster, a task definition, a service, a load balancer, a listener, and a target group.
That’s the AWS Cloud Development Kit (CDK): infrastructure in a real programming language, with sensible defaults built in. It’s powerful — and like every abstraction, it hides things you still need to understand.
What you’ll walk away with
- 🧱 CDK apps, stacks, and constructs — and the three construct levels
- 🌍 Environments: accounts and Regions
- 🔧 The workflow:
cdk synth,cdk diff, andcdk deploy - ♻️ Writing reusable constructs
- 🚀 CDK Pipelines for self-updating deployments
- 🔗 How CDK relates to CloudFormation
How CDK works
Your code (TypeScript, Python, Java, C#, Go)
|
| cdk synth
v
CloudFormation template(s) + assets (Docker images, Lambda code)
|
| cdk deploy
v
CloudFormation stack(s) in your account
CDK doesn’t replace CloudFormation — it generates it. Everything you learned in Part 1 still applies: stacks, change sets, rollbacks, drift, and DeletionPolicy.
Apps, stacks, and constructs
- App: the root of your CDK program. It contains one or more stacks.
- Stack: maps one-to-one to a CloudFormation stack, deployed to one account and Region.
- Construct: the building block. Every resource — and every group of resources — is a construct. Constructs nest inside each other to form a tree.
const app = new cdk.App();
new NetworkStack(app, 'orders-network-dev', { env: devEnv });
new ServiceStack(app, 'orders-service-dev', { env: devEnv });
The three construct levels
- L1 — CloudFormation resources: named
Cfn*, likeCfnBucket. A direct, one-to-one mapping of every CloudFormation property. Full control, no defaults. - L2 — curated constructs: like
s3.Bucketorec2.Vpc. Sensible defaults, convenience methods, and type-safe properties. - L3 — patterns: like
ApplicationLoadBalancedFargateService. Whole architectures in one construct.
The killer feature: grant methods
L2 constructs can wire up IAM permissions for you:
const bucket = new s3.Bucket(this, 'Uploads', {
encryption: s3.BucketEncryption.S3_MANAGED,
blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
enforceSSL: true,
versioned: true,
removalPolicy: cdk.RemovalPolicy.RETAIN,
});
const fn = new lambda.Function(this, 'Resize', { /* ... */ });
bucket.grantRead(fn);
grantRead writes a least-privilege policy on the function’s role — scoped to exactly this bucket. No hand-written JSON, no wildcards.
Environments
An environment is an account and Region pair that a stack deploys to:
const devEnv = { account: '111111111111', region: 'us-east-1' };
const prodEnv = { account: '222222222222', region: 'us-east-1' };
new ServiceStack(app, 'orders-dev', { env: devEnv, desiredCount: 1 });
new ServiceStack(app, 'orders-prod', { env: prodEnv, desiredCount: 4 });
- Explicit environments let CDK look up real values, like existing VPCs and AZs, at synth time.
- Environment-agnostic stacks, with no
env, can deploy anywhere but can’t use lookups.
Bootstrapping
Before the first deploy, each environment needs bootstrapping:
cdk bootstrap aws://111111111111/us-east-1
This creates a CDKToolkit stack with an S3 bucket and an ECR repository for assets, plus IAM roles that CDK uses to deploy. For cross-account deployments, bootstrap target accounts with --trust to let a pipeline account deploy into them.
The workflow: synth, diff, deploy
cdk synth # generate CloudFormation into cdk.out/
cdk diff orders-dev # compare with what's deployed
cdk deploy orders-dev # deploy through CloudFormation
cdk destroy orders-dev # delete the stack
cdk synth
Runs your code and writes templates and assets to cdk.out/. If your code has a bug, it fails here — before touching AWS. Read the generated template at least once; it’s the best way to understand what CDK is doing for you.
cdk diff
Shows resource changes, IAM and security group changes, and — importantly — replacements. Treat it like a Terraform plan.
cdk deploy
Uploads assets — like building and pushing your Docker image to the bootstrap ECR repository — then creates or updates the stack through a change set. By default, it asks for approval when security-related changes appear.
Engineer’s note:
cdk watchand hotswap deployments are great for fast feedback in development. They intentionally skip CloudFormation for some changes, so never use them against production.
Reusable constructs
Your own constructs are just classes. Package your team’s standards once, and reuse them everywhere:
export interface SecureBucketProps {
readonly retainOnDelete?: boolean;
}
export class SecureBucket extends Construct {
public readonly bucket: s3.Bucket;
constructor(scope: Construct, id: string, props: SecureBucketProps = {}) {
super(scope, id);
this.bucket = new s3.Bucket(this, 'Bucket', {
encryption: s3.BucketEncryption.KMS_MANAGED,
blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
enforceSSL: true,
versioned: true,
lifecycleRules: [{ noncurrentVersionExpiration: cdk.Duration.days(30) }],
removalPolicy: props.retainOnDelete === false
? cdk.RemovalPolicy.DESTROY
: cdk.RemovalPolicy.RETAIN,
});
}
}
Now every team gets encrypted, private, versioned buckets by writing new SecureBucket(this, 'Reports'). Publish constructs as packages to share them across repositories.
Testing infrastructure
Because it’s code, you can unit test it:
const template = Template.fromStack(stack);
template.hasResourceProperties('AWS::S3::Bucket', {
VersioningConfiguration: { Status: 'Enabled' },
});
Tools like cdk-nag check your stacks against security rule packs at synth time.
Aspects
Aspects visit every construct in a scope — useful for organization-wide rules, like “add these tags everywhere” or “fail synth if any bucket is unencrypted.”
CDK Pipelines
CDK Pipelines is a construct library for continuous delivery of CDK apps through AWS CodePipeline:
const pipeline = new pipelines.CodePipeline(this, 'Pipeline', {
synth: new pipelines.ShellStep('Synth', {
input: pipelines.CodePipelineSource.connection('acme/orders-infra', 'main', {
connectionArn: 'arn:aws:codeconnections:us-east-1:111122223333:connection/abc',
}),
commands: ['npm ci', 'npm test', 'npx cdk synth'],
}),
});
pipeline.addStage(new OrdersStage(this, 'Dev', { env: devEnv }));
pipeline.addStage(new OrdersStage(this, 'Prod', { env: prodEnv }), {
pre: [new pipelines.ManualApprovalStep('PromoteToProd')],
});
- Self-mutating: when you change the pipeline’s code, it updates itself first.
- Stages deploy the same app to multiple environments, in order.
- Pre and post steps add approvals and smoke tests.
Phase 7 covers AWS-native CI/CD and GitHub Actions in depth.
CDK vs. CloudFormation vs. Terraform
- CloudFormation: declarative YAML, no extra tooling, AWS-managed state. Verbose for large systems.
- CDK: real languages, loops, types, tests, and high-level constructs — compiled into CloudFormation. Great when your team writes code every day.
- Terraform: a declarative language across many providers, with a fast plan workflow and self-managed state.
Watch out: “It’s just code” can tempt teams into clever abstractions nobody can follow. Keep stacks simple, prefer composition, and make generated templates easy to review.
Common mistakes
- Not reading
cdk diff, and missing a resource replacement. - Forgetting to bootstrap an account or Region.
- Default removal policies on data that should be retained.
- Changing a construct’s ID, which changes the logical ID and replaces the resource.
- Hotswap deploys against production.
- Over-abstracted constructs that hide important settings.
Key takeaways
- CDK turns code into CloudFormation; everything about stacks still applies.
- L1 is raw, L2 is curated with defaults, L3 is a whole pattern.
grant*methods generate least-privilege IAM policies.- Bootstrap every environment; use explicit environments for lookups.
synth,diff, anddeployare your plan-and-apply workflow.- Package standards as reusable constructs, and test them.
Quick self-check
Test yourself before moving on:
- What does
cdk synthproduce? - Which construct level gives you sensible defaults and grant methods?
- You renamed a construct’s ID from
DbtoDatabase. What happens on deploy? - What does
cdk bootstrapcreate?
Answers
- CloudFormation templates and assets in
cdk.out/. - L2.
- Its logical ID changes, so CloudFormation replaces the resource. Check
cdk difffirst. - An assets bucket, an ECR repository, and deployment roles in the
CDKToolkitstack.
What’s next
In Part 4, we automate what happens inside and around your resources with AWS Systems Manager: Parameter Store, Session Manager, Run Command, Patch Manager, Automation, State Manager, and more.
CDK, Terraform, or CloudFormation — which does your team use? Tell me why in the comments.