The AWS CDK

Intermediate · 27 min

Defining AWS infrastructure in a programming language: apps, stacks and constructs, synth and bootstrap, grants, logical IDs, removal policies and tests.

Before thisCloudFormation templates and stacksChanging stacks safelySQS queues

Be A Better Dev · 27 min · from 0:16

The AWS CDK

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Be A Better DevReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • CDK code runs on your machine and produces CloudFormation templates. CloudFormation still does the deployment and the rollback.
  • L1 constructs map one to one to resources, L2 constructs add defaults and helper methods, and L3 patterns wire several resources together.
  • Methods such as grant helpers and event sources write IAM policies for you. Read what they generated.
  • Logical IDs derive from the construct's ID and path. Renaming or moving a construct can replace the resource.
  • Check removal policies on stateful resources, and review cdk diff before deploying.
  • An environment must be bootstrapped once per account and Region, and the bootstrap roles are powerful.

When YAML stops scaling

A template is explicit, and that is the problem at size. A queue with a dead-letter queue, a function that consumes it, its role and its mapping run to well over a hundred lines, most of it the same in every project, and IAM statements written by hand tend toward *.

The AWS Cloud Development Kit (CDK) lets you write that in TypeScript, Python, Java, C# or Go, with functions, loops, types and shared libraries. The key point to hold on to: your program doesn’t create anything. It synthesizes CloudFormation templates, and CloudFormation deploys them. Think of a compiler. You write the higher-level language; the machine still runs the output.

An app contains stacks, and stacks contain constructs, which are reusable building blocks:

  • L1 (CfnQueue): one-to-one with a CloudFormation resource.
  • L2 (Queue): the same resource with sensible defaults and methods.
  • L3 patterns: several resources wired for a purpose.

A worked example

const { App, Stack, Duration } = require('aws-cdk-lib');
const sqs = require('aws-cdk-lib/aws-sqs');
const lambda = require('aws-cdk-lib/aws-lambda');
const { SqsEventSource } = require('aws-cdk-lib/aws-lambda-event-sources');

class OrdersStack extends Stack {
  constructor(scope, id, props) {
    super(scope, id, props);
    const dlq = new sqs.Queue(this, 'DeadLetters',
      { retentionPeriod: Duration.days(14) });
    const queue = new sqs.Queue(this, 'Orders', {
      visibilityTimeout: Duration.seconds(180),
      deadLetterQueue: { queue: dlq, maxReceiveCount: 5 },
    });
    const worker = new lambda.Function(this, 'Worker', {
      runtime: lambda.Runtime.NODEJS_24_X,
      handler: 'index.handler',
      code: lambda.Code.fromInline('exports.handler = async () => {};'),
      timeout: Duration.seconds(30),
    });
    worker.addEventSource(
      new SqsEventSource(queue, { reportBatchItemFailures: true }));
  }
}

const app = new App();
new OrdersStack(app, 'OrdersStack');
app.synth();

I ran this with aws-cdk-lib 2.278.0. The resulting template held six resources:

DeadLettersBBF8BAAB                    AWS::SQS::Queue
OrdersA9B65338                         AWS::SQS::Queue
WorkerServiceRole8543584E              AWS::IAM::Role
WorkerServiceRoleDefaultPolicy...      AWS::IAM::Policy
Worker11F36D0F                         AWS::Lambda::Function
WorkerSqsEventSourceOrdersStack...     AWS::Lambda::EventSourceMapping

I wrote three things and got six. The role carries AWSLambdaBasicExecutionRole, and the generated policy allows receive, delete, change visibility and the two lookup actions on that queue only. One line, addEventSource, did the wiring. Run cfn-lint on the output if you like; it passed with one warning about a redundant dependency.

Logical IDs are the sharp edge

Those suffixes are hashes of each construct’s path in the tree. I changed one string, the construct ID 'Orders' to 'OrderQueue', and synthesized again:

before   OrdersA9B65338
after    OrderQueue39B99167

To CloudFormation that is a different resource: create one, delete the other. Moving a construct inside another one does the same. Both queues in my output also had DeletionPolicy: Delete. Other resources have other defaults, so set removalPolicy explicitly on anything with data.

The workflow

  1. cdk bootstrap, once per account and Region, creates a stack with the bucket, repository and roles that deployments use. Those roles are powerful; control who can assume them.
  2. cdk synth writes templates to cdk.out.
  3. cdk diff compares them with what is deployed. Read it, IAM changes first.
  4. cdk deploy publishes assets such as function code and container images, then runs CloudFormation.

Testing and habits

Because infrastructure is code, you can test it. Fine-grained assertions check that the template has a property with a value; snapshot tests flag any change. Pin the library version, since an upgrade can change output. Group stacks by lifetime, keep stateful resources apart from stateless ones, avoid logic that looks things up at deploy time, and drop to L1 with an escape hatch when an L2 lacks a setting.

CDK or Terraform? CDK is AWS-centred, uses general programming languages and keeps state in CloudFormation. Terraform covers many providers and manages its own state.

Environments, context and assets

A stack is deployed into an environment, meaning one account and Region. You can leave it unset, which keeps the template generic but limits what the CDK can know at synth time, or name it explicitly, which is the safer habit for production. Typical code creates the same stack class twice, once for staging and once for production, with different properties. The differences are then visible in one file instead of scattered across parameter values.

Some constructs look things up in your account while synthesizing, such as which Availability Zones exist or an image ID. The CDK caches those answers in cdk.context.json. Commit that file. Without it, the same code can produce a different template next month because the answer changed, and an unplanned new image ID can replace running instances. Refresh cached values deliberately, and read the diff when you do.

Function code and container images are assets: files the CDK packages and uploads to the bootstrap bucket or repository before CloudFormation runs. That is convenient, and it means a deployment needs build tooling, not only the template.

About the video

The embed is a clip (0:16 to 27:15) of Be A Better Dev’s “AWS CDK Crash Course for Beginners”, March 2024. Its chapters in that range explain what CDK is, compare manual setup and CloudFormation, describe the developer workflow, constructs, Construct Hub, the reference documentation, stacks and apps. The hands-on TypeScript build follows on YouTube if you want it. I judged it from chapters and description only, since transcripts couldn’t be fetched. English was judged from the “English (US) original” audio track.

What was run: the app, the resource list, the IAM statement and the logical ID change are real output from synthesizing locally with Node. Nothing was deployed, and the cdk CLI commands were not run. Bootstrapping and testing notes are from the AWS docs, checked 2026-11-29.

Where this fits

CDK is general purpose. For serverless applications, AWS SAM offers a shorter template and local testing.

Check yourself

  1. 01You rename a construct from Orders to OrderQueue in a refactor with no other change. What would a deployment do?

    The logical ID changes, so CloudFormation creates a new queue and deletes the old one, along with whatever was in it. cdk diff shows this before you deploy. Keep IDs stable or use refactoring tools that preserve the resource.

  2. 02Your app synthesized fine yet the deployment failed. Is that possible?

    Yes. Synth only produces a template. Permissions, quotas, name clashes and many property values are checked when CloudFormation and the services act.

  3. 03A teammate calls bucket.grantReadWrite(fn) everywhere. What should a reviewer still check?

    The generated policy. The helper scopes to that bucket, but read and write may be more than the function needs, and the deployment's IAM changes should be reviewed like hand-written ones.

  4. 04Why does a unit test with assertions on the synthesized template not replace a deployment test?

    It proves your code produces the template you expect, not that the resources work together in AWS. You still need to deploy somewhere and exercise the system.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark