Skip to content
Tutorials Center
My learning

Topics

Lesson 53 of 70 ยท Infrastructure as code

AWS CDK

Learn the AWS Cloud Development Kit: apps, stacks and L1, L2, L3 constructs, cdk synth and deploy, TypeScript and Python code, and tests, with a runnable synth stand-in.

Writing a CloudFormation template by hand gets long fast. A secure bucket, a function and the permission that lets one read the other can run to a hundred lines of YAML, with every ARN spelled out and every logical ID invented by you. A real programming language is better at repetition, defaults and abstraction than YAML is.

The AWS Cloud Development Kit (CDK) lets you describe infrastructure in TypeScript, Python, Java, C# or Go. When you run it, your program builds a tree of objects and then synthesizes a CloudFormation template from that tree. CloudFormation still does the real work of creating resources, so everything in CloudFormation (stacks, change sets, rollback, drift) still applies. CDK is a code generator in front of it.

CDK needs Node.js tooling and an AWS account for deploys, so its code and commands here are read-only. The runnable examples are a miniature Python stand-in for the CDK idea: construct classes that produce a CloudFormation template, with tests. It is much simpler than the real library and is not the real API. Each section says what is real and what is the stand-in.

From code to cloud

flowchart LR
    A["Your CDK app<br/>(TypeScript, Python, ...)"] -- "cdk synth" --> B["CloudFormation template<br/>in cdk.out"]
    B -- "cdk deploy" --> C["CloudFormation stack"]
    C --> D["Real AWS resources"]

CDK turns code into a template; CloudFormation turns the template into resources.

The everyday commands (read-only here):

Terminal
npm install -g aws-cdk
mkdir uploads && cd uploads
cdk init app --language typescript

cdk bootstrap aws://123456789012/eu-west-1   # once per account and Region
cdk synth      # print the CloudFormation template
cdk diff       # compare with what is deployed
cdk deploy     # create or update the stack
cdk destroy    # delete the stack

cdk bootstrap creates a small stack (named CDKToolkit) with a storage bucket and roles that CDK uses to upload files such as Lambda code and to deploy. You run it once for each account and Region you deploy to. cdk diff is the CDK equivalent of reading a change set before you apply it.

The construct tree

Everything in CDK is a construct. Constructs form a tree:

  • The App is the root.
  • A Stack is a child of the app. One stack becomes one CloudFormation stack.
  • Everything else (a bucket, a function, a VPC, your own building blocks) is a construct inside a stack, and may contain further constructs.

Each construct is created with new Thing(scope, id, props) in TypeScript (Thing(scope, id, **props) in Python). scope is the parent and id is a name that must be unique among its siblings. The ids from the root down to a construct form its path, and CDK derives the CloudFormation logical ID from the path: the path pieces joined together plus a short hash (eight hex characters), for example UploadsF3A1B2C4 for a bucket whose construct id is Uploads. You never write logical IDs yourself.

That has one important consequence: renaming a construct id changes its logical ID. To CloudFormation, a resource with a new logical ID is a brand-new resource, so the old one is deleted (or retained) and a new one created. Treat construct ids of stateful resources (buckets, tables, databases) as permanent.

The three levels of constructs

Level Also called What it is Example
L1 Cfn constructs A one-to-one wrapper of a CloudFormation resource, with every property and no defaults s3.CfnBucket
L2 Curated constructs A friendly class with good defaults, helper methods and sensible security s3.Bucket, lambda.Function
L3 Patterns Several resources wired into a common solution ApplicationLoadBalancedFargateService

Start with L2 constructs. Drop to an L1 only when a feature has no L2 support yet. L3 patterns save the most typing but make choices for you, so check what they create.

A small TypeScript stack (read-only):

TypeScript
import * as cdk from 'aws-cdk-lib';
import * as s3 from 'aws-cdk-lib/aws-s3';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import { Construct } from 'constructs';

export class UploadsStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    const bucket = new s3.Bucket(this, 'Uploads', {
      versioned: true,
      blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
    });

    const processor = new lambda.Function(this, 'Processor', {
      runtime: lambda.Runtime.PYTHON_3_13,
      handler: 'app.handler',
      code: lambda.Code.fromAsset('lambda'),
    });

    bucket.grantRead(processor);
  }
}

const app = new cdk.App();
new UploadsStack(app, 'UploadsStack');

The same in Python:

Python
from aws_cdk import App, Stack, aws_s3 as s3, aws_lambda as _lambda
from constructs import Construct


class UploadsStack(Stack):
    def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        bucket = s3.Bucket(
            self, "Uploads",
            versioned=True,
            block_public_access=s3.BlockPublicAccess.BLOCK_ALL,
        )
        processor = _lambda.Function(
            self, "Processor",
            runtime=_lambda.Runtime.PYTHON_3_13,
            handler="app.handler",
            code=_lambda.Code.from_asset("lambda"),
        )
        bucket.grant_read(processor)


app = App()
UploadsStack(app, "UploadsStack")
app.synth()

Count what you did not write. The single line bucket.grantRead(processor) becomes an IAM policy with the right actions and the bucket ARNs, attached to the function's role. The function got an execution role without you asking. The bucket got the settings you passed, and the real L2 bucket also defaults to retaining the bucket when the stack is deleted. These "defaults and helpers" are why people choose CDK.

A miniature synth

The real cdk synth is large. This stand-in captures its core: a construct tree, L1 resources, L2 constructs that create L1 children with defaults, a grant_read helper that edits another construct's role policy, and logical IDs derived from the path with a hash. It outputs a CloudFormation-shaped template. The real CDK differs in many details (tokens, asset handling, metadata), and its hashes are not the ones printed here.

Python Synthesize a template from a construct tree

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Three CDK resources of your code became four template resources: the bucket, the function, the function's role and the policy that grant_read created. The logical IDs are the construct ids glued together plus a hash of the path, and the Resource child is hidden from the name, which mirrors how real CDK names things. The policy uses Fn::GetAtt to point at the bucket's ARN, so CloudFormation orders the resources correctly just as it did in the last lesson.

Writing your own constructs

A construct is just a class. Wrapping a repeated design in your own construct (an L3 of your own) gives your team a reusable, tested building block: "a queue with a dead-letter queue and a retry limit", "a bucket that follows the company's rules". Because CDK is real code, you also get loops, functions, conditionals and package managers to share constructs across projects.

Two notes on how CDK differs from writing templates by hand:

  • Values are not always known at synth time. A bucket's name or ARN is only known after deployment, so CDK uses placeholders called tokens and writes Ref and GetAtt into the template. Do not try to print a resource name in your program and expect the real value.
  • Environment matters. Passing an explicit env (account and Region) to a stack lets CDK look up existing resources, such as a VPC, at synth time. Without it the stack is environment-agnostic and some lookups are unavailable.

Testing infrastructure

Because the output is a template, you can test it without deploying anything. The real CDK offers an assertions module (read-only):

Python
from aws_cdk.assertions import Template

template = Template.from_stack(stack)
template.resource_count_is("AWS::S3::Bucket", 1)
template.has_resource_properties(
    "AWS::S3::Bucket",
    {"VersioningConfiguration": {"Status": "Enabled"}},
)

There are two common kinds. Fine-grained assertions check specific properties (the bucket must have versioning). Snapshot tests compare the whole template with a stored copy to catch unexpected changes. Tests like these run in seconds in a normal test runner and protect rules such as "no public buckets" before a deploy.

Tests on a synthesized template

This stand-in builds a small L3-style construct (a queue with a dead-letter queue), writes the same two assertion helpers over the synthesized template, and then shows why construct ids must stay stable: renaming one changes the logical ID.

Python Assertion tests and the cost of renaming an id

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first three tests pass, and the fourth fails on purpose to show what a failing test reports. The rename demo is the important part: changing one id from Orders to OrderQueue shares no logical IDs with the old version, so CloudFormation would delete both queues (and any messages in them) and create two new ones. cdk diff would show this before you deploy. If you must rename, real CDK lets you pin the old logical ID with an override on the underlying L1 resource.

CDK, CloudFormation and the others

CDK is not a separate engine. It is a way to write CloudFormation, so you keep stacks, rollback and drift detection, and you inherit CloudFormation's limits (a stack holds a few hundred resources at most, and some changes are slow). The next lesson covers Terraform, which is a different engine with its own state file.

Practical advice:

  • Keep one app, several stacks, split by lifecycle: for example a network stack that changes rarely and application stacks that change daily.
  • Commit the generated cdk.context.json, which records lookups, so synth stays reproducible.
  • Review cdk diff output in pull requests the way you review code.
  • Use multi-account governance so each environment deploys to its own account.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does cdk synth produce?

    Synthesizing runs your program and writes the CloudFormation template. cdk deploy then hands that template to CloudFormation.
  2. 2. Which construct level is a one-to-one wrapper of a single CloudFormation resource with no defaults?

    L1 constructs such as CfnBucket map directly to resource types. L2 constructs add defaults and helpers, and L3 constructs combine several resources.
  3. 3. What is the risk of renaming the id of a construct for a database or bucket?

    Logical IDs come from the construct path. A changed id gives a new logical ID, which CloudFormation treats as removing one resource and creating another.
  4. 4. What does bucket.grantRead(function) do?

    Grant helpers are a major benefit of L2 constructs; they write a least-privilege IAM statement for you and attach it to the role.
  5. 5. How can you check that a bucket has versioning turned on without deploying anything?

    The template is plain data, so assertion tests and snapshot tests can run locally in seconds.

Summary

  • CDK lets you describe infrastructure in a programming language; cdk synth produces a CloudFormation template and cdk deploy has CloudFormation apply it.
  • Apps contain stacks, and stacks contain constructs: L1 (raw Cfn resources), L2 (friendly defaults and helpers such as grantRead) and L3 (patterns, including your own).
  • Logical IDs come from construct paths, so keep ids of stateful resources stable and read cdk diff before every deploy.
  • Run cdk bootstrap once per account and Region; commit cdk.context.json.
  • Test the synthesized template with fine-grained assertions and snapshots before deploying.

Next: Terraform on AWS