Lesson 1 of 1 AWS CDK

Defining Infrastructure in Code with the AWS CDK

This lesson explains how the AWS Cloud Development Kit (AWS CDK) lets you define infrastructure in TypeScript, Python, Java, C# or Go, and turns that code into CloudFormation templates.

Learning outcomes

After completing this lesson, you will be able to:

  • Describe how apps, stacks and constructs are related.
  • Describe the purpose of the CDK CLI commands, including cdk bootstrap, cdk synth, cdk diff and cdk deploy.
  • Explain how CDK assertions and removal policies test and protect infrastructure.

Apps, stacks and constructs

The AWS Cloud Development Kit (CDK) defines infrastructure in a programming language, such as Python or TypeScript, instead of in a template. A CDK app is a program that contains one or more stacks, and each stack becomes one CloudFormation stack when deployed. Stacks are built from constructs, classes that represent one or more AWS resources. Constructs come at three levels of abstraction.

L1 constructs, whose names begin with Cfn, map exactly to CloudFormation resource types and expose every property, but provide no defaults or helpers. L2 constructs, such as s3.Bucket and _lambda.Function, are the ones developers use most. They apply secure defaults and offer methods that express intent: table.grant_read_data(fn) adds a least-privilege IAM policy to the function's role without writing JSON. L3 constructs, or patterns, combine several resources into a common architecture, such as a Fargate service behind an Application Load Balancer, in a single declaration. The following table summarises the levels.

LevelWhat it isExample
L1A direct mapping to a CloudFormation resourceCfnBucket
L2A resource with sensible defaults and helper methodstable.grant_read_data(fn) writes the IAM policy for you
L3 (patterns)Several resources combined into a common architectureA load-balanced Fargate service

The CDK also packages Lambda code and Docker images as assets, uploading them during deployment.

Example. A table and function in Python, with permissions granted in one line:

from aws_cdk import Duration, Stack, aws_dynamodb as ddb, aws_lambda as _lambda
from constructs import Construct

class OrdersStack(Stack):
    def __init__(self, scope: Construct, construct_id: str, **kwargs):
        super().__init__(scope, construct_id, **kwargs)
        table = ddb.Table(
            self, "Orders",
            partition_key=ddb.Attribute(name="pk", type=ddb.AttributeType.STRING),
            billing_mode=ddb.BillingMode.PAY_PER_REQUEST,
        )
        fn = _lambda.Function(
            self, "Handler",
            runtime=_lambda.Runtime.PYTHON_3_13,
            handler="app.handler",
            code=_lambda.Code.from_asset("src"),
            timeout=Duration.seconds(10),
            environment={"TABLE_NAME": table.table_name},
        )
        table.grant_read_write_data(fn)

The CDK CLI

The CDK CLI turns the program into deployed resources. cdk init creates a project with the structure the CLI expects. Before the first deployment to an account and Region, cdk bootstrap creates a CloudFormation stack named CDKToolkit, which contains an S3 bucket and an ECR repository for assets and the IAM roles that deployments use; deploying to an environment that has not been bootstrapped fails.

cdk synth runs the program and writes the resulting CloudFormation templates to the cdk.out directory, which is useful for reviewing exactly what will be deployed. cdk diff compares the synthesised templates with the deployed stacks and highlights changes to IAM permissions and security groups separately, so broadened access is noticed before deployment. cdk deploy uploads the assets and deploys the stacks through CloudFormation, and cdk destroy deletes them. The following table summarises the commands.

CommandWhat it does
cdk initStarts a project
cdk bootstrapCreates the bucket and roles the CDK needs; run once per account and Region
cdk synthGenerates the CloudFormation template
cdk diffCompares with what is deployed, highlighting security changes such as new IAM permissions
cdk deployDeploys the stack

Because the output is CloudFormation, deployments get change sets and rollback, and CDK Pipelines can build self-updating CI/CD pipelines.

Testing and protecting infrastructure

Because a CDK app is ordinary code, its output can be tested before anything is deployed. The CDK assertions module synthesises a stack inside a normal unit test, run with a framework such as pytest or Jest, and checks the resulting template. Template.from_stack(stack) captures the template, and methods such as has_resource_properties and resource_count_is verify, for example, that a table uses on-demand billing or that exactly one function is created. These tests need no AWS account and catch unintended changes to infrastructure in the same way that unit tests catch changes to application code.

A removal policy decides what happens to a resource when it is removed from the stack or the stack is deleted, and the CDK writes it into the template as the resource's DeletionPolicy and UpdateReplacePolicy. RemovalPolicy.RETAIN keeps the resource and its data, RemovalPolicy.SNAPSHOT keeps a snapshot for resources that support one, and RemovalPolicy.DESTROY deletes it. Stateful L2 constructs, such as S3 buckets and DynamoDB tables, default to RETAIN, so development stacks that should be removed completely set DESTROY explicitly.

Worked example

Reading a cdk diff

Before deploying, a developer runs cdk diff after adding one line, table.grant_read_write_data(fn):

IAM Statement Changes
+ Allow dynamodb:BatchGetItem, dynamodb:GetItem, dynamodb:PutItem, dynamodb:Query, ...
    on OrdersTable  to  OrdersFunction/ServiceRole

Resources
[~] AWS::IAM::Policy OrdersFunction/ServiceRole/DefaultPolicy

One line produced a least-privilege policy scoped to that table, which the diff makes visible for review. If the diff had shown a table being replaced, the developer would stop and investigate. Deploying to a new account first requires cdk bootstrap, a common first error for new CDK users.

Check yourself

What must be done once in each account and Region before the CDK can deploy there?

Show answer

Run cdk bootstrap. It creates the resources the CDK needs for deployment, such as an S3 bucket for assets and IAM roles.

Exam Tips

Remember for the exam

  • To define infrastructure with loops, classes and type checking, use the AWS CDK.
  • "Deployment fails because the toolkit stack is missing" means you must run cdk bootstrap.
  • To generate the CloudFormation template, run cdk synth.
  • To keep a table or bucket when the stack is deleted, set RemovalPolicy.RETAIN.
  • To unit test infrastructure code, use CDK assertions.