What Is AWS CDK? Tutorial in TypeScript and Python, Install on Windows, CLI Commands, Constructs and CDK vs Terraform

Logeshwaran
—

The AWS Cloud Development Kit (CDK) lets you define your AWS infrastructure, such as buckets, databases, Lambda functions, APIs, networks and permissions, in a real programming language: TypeScript, JavaScript, Python, Java, C# or Go. You write a few lines like new s3.Bucket(this, "Uploads"), and the CDK turns them into an AWS CloudFormation template (the "synth" step), then deploys that template so CloudFormation creates and updates the real resources. Because it is code, you get loops, functions, classes, autocomplete, unit tests and code review, and high-level building blocks called constructs that set sensible defaults for you (one line can create a bucket with encryption, or a Lambda function with its IAM role). The CDK is free and open source; you pay only for the AWS resources you create, plus a few cents for the S3 bucket and ECR repository that cdk bootstrap sets up for deployment files. Below: what the CDK is and how it works, constructs L1, L2 and L3, a step-by-step tutorial in TypeScript and Python, every CLI command, CDK vs CloudFormation, Terraform, SAM and Pulumi, testing and pipelines, and fixes for the errors you will hit first.

The furniture store's developer had built everything in the AWS console: the S3 bucket for product photos, the Lambda function that resized them, the API, the IAM roles, the Batch queue for renders. Then the owner asked for a second copy of the whole thing for testing. It took the developer two days of clicking and a page of notes, and the copy still differed from production in three places nobody could find. "There has to be a way to write this down once," he told Ethan. Jake, who was there to collect the old office printer, asked the obvious: "Can't you just copy and paste it, like a document?" With the CDK, you basically can.

⚡ Quick Answer

• What it is: infrastructure as code in TypeScript, Python, Java, C#, Go or JavaScript, deployed through CloudFormation. Explained.

• Price: free and open source; you pay for the resources, plus cents for the bootstrap bucket. Costs.

• Start: npm install -g aws-cdk, cdk init, cdk bootstrap, cdk deploy. Tutorial.

• Which tool: CDK for AWS-only teams who like code; Terraform for multi-cloud; SAM for simple serverless. Compare.

How it works · Constructs · CLI commands · Concepts · Tests and pipelines · Errors · FAQ.

New to infrastructure as code? The cards below explain IaC, CloudFormation stacks, Lambda, IAM and API Gateway, the pieces the CDK writes for you.

🧭 NEW HERE? READ THESE FIRST

These five pages explain what the CDK builds and deploys:

📌 Bookmark this; the tutorial, the CLI table and the error fixes are the parts you will come back for.

What is the AWS CDK?

The AWS Cloud Development Kit is an open-source framework for infrastructure as code. Instead of clicking through the AWS console, or writing long JSON or YAML templates, you describe your infrastructure as classes and objects in a language you already know. A CDK program is called an app; it contains one or more stacks (each becomes one CloudFormation stack), and each stack contains constructs, the building blocks that represent AWS resources.

Three things make the CDK different from writing CloudFormation by hand:

  • It is real code. You can use variables, loops, if statements, functions and classes. Creating ten similar queues is a loop, not ten copies of a YAML block. Your editor autocompletes every property and flags typos before you deploy.
  • Constructs have good defaults. The higher-level constructs know AWS's best practices. new s3.Bucket(this, "Photos", { encryption: s3.BucketEncryption.S3_MANAGED }) gives you a private, encrypted bucket; bucket.grantRead(myFunction) writes a least-privilege IAM policy for you. Fifty lines of CDK often become five hundred lines of CloudFormation.
  • It still uses CloudFormation underneath. The CDK does not call AWS APIs to create resources directly. It generates a CloudFormation template and hands it to CloudFormation, so you get CloudFormation's change sets, rollback on failure, drift detection and stack history, and your platform team can still read the generated template.

What you would use the CDK for: any AWS environment you want to be able to recreate exactly, such as production and test copies of an application, a serverless API, a data pipeline, a whole account baseline of networks and roles, or reusable patterns your company shares between teams as a library.

Jake: "So it's a recipe for the whole kitchen. Hand it to someone and they get the same kitchen."

Ethan: "And if you want a second kitchen for testing, you run the recipe again with a different name."

How the CDK works, step by step

Here is the path from your code to running resources:

  1. You write an app in your language, with stacks and constructs.
  2. You run cdk synth (or cdk deploy, which synthesizes first). The CDK runs your program, which builds a tree of constructs in memory.
  3. The CDK produces a cloud assembly in the cdk.out folder: a CloudFormation template for each stack, plus assets, such as zipped Lambda code and Docker images, that the templates refer to.
  4. Bootstrap resources receive the assets. The first time you deploy to an account and Region, cdk bootstrap creates a stack called CDKToolkit with an S3 bucket for files, an ECR repository for container images, and IAM roles the CDK uses to deploy.
  5. The CDK uploads the assets to that bucket and repository.
  6. The CDK asks CloudFormation to deploy each template, as a change set, using the bootstrap roles.
  7. CloudFormation creates, updates or deletes resources to match the template, in dependency order, and rolls back if something fails.
  8. Outputs come back, such as your API URL or bucket name, printed in your terminal.

Because every deployment goes through CloudFormation, a change you make in code becomes a precise set of changes to your resources, which cdk diff shows you before anything happens.

Constructs: L1, L2 and L3

Constructs come in three levels, and knowing which is which explains most CDK code you will read:

LevelWhat it isExampleUse it when
L1 (Cfn resources)A one-to-one mapping of a CloudFormation resource, every property exposed, no defaultss3.CfnBucketYou need a brand-new feature or a property the L2 does not expose
L2 (curated)A friendly API with secure defaults and helper methods such as grant and addEventNotifications3.Bucket, lambda.FunctionAlmost always; this is everyday CDK
L3 (patterns)Several resources wired together for a common architectureecs_patterns.ApplicationLoadBalancedFargateServiceThe pattern matches what you want to build

You can also write your own constructs: a class that bundles your company's standard bucket, alarm and backup settings, published as a library that every team imports. The Construct Hub is a public catalog of open-source construct libraries from AWS, partners and the community, and tools such as cdk-nag check your constructs against security and compliance rules while you synthesize.

How much does the AWS CDK cost?

The CDK itself is free. It is open-source software that runs on your computer or build server. What you pay for:

  • The AWS resources you define, at their normal prices, exactly as if you had created them in the console.
  • CloudFormation: free for AWS resource types (charges apply only to third-party resource types and hooks).
  • Bootstrap resources: the CDKToolkit S3 bucket and ECR repository store your deployment assets; for most projects this is a few megabytes to a few gigabytes, which costs cents a month. Old assets can pile up over years of deployments, so add lifecycle rules or clean them out occasionally.
  • Your build environment: nothing extra if you deploy from your laptop; normal CodeBuild or CI minutes if you deploy from a pipeline.

AWS CDK tutorial: your first stack in TypeScript or Python

This builds a small but real app: an S3 bucket for uploads and a Lambda function that runs whenever a file arrives.

  1. Install Node.js (a current LTS version). The CDK CLI runs on Node.js even if you write your app in Python, Java, C# or Go.
  2. Install the CDK CLI: npm install -g aws-cdk, then check it with cdk --version.
  3. Set up AWS credentials for the account you will deploy to, with aws configure sso or aws configure, and test them with aws sts get-caller-identity.
  4. Create a project: mkdir photo-app && cd photo-app, then cdk init app --language typescript (or --language python). For Python, activate the virtual environment it creates and run pip install -r requirements.txt.
  5. Bootstrap the account and Region once: cdk bootstrap aws://111122223333/us-east-1.
  6. Write your stack (code below) in lib/photo-app-stack.ts or photo_app/photo_app_stack.py, and the function's code in a lambda folder.
  7. Synthesize and review: cdk synth prints the CloudFormation template; cdk diff shows what will change.
  8. Deploy: cdk deploy. It shows IAM and security group changes and asks you to confirm, then creates the stack.
  9. Test it: upload a file to the bucket and watch the function's log in CloudWatch.
  10. Clean up when you are done: cdk destroy.

The stack in TypeScript:

import { Stack, StackProps, RemovalPolicy, Duration, CfnOutput } from "aws-cdk-lib";
import { Construct } from "constructs";
import * as s3 from "aws-cdk-lib/aws-s3";
import * as lambda from "aws-cdk-lib/aws-lambda";
import * as s3n from "aws-cdk-lib/aws-s3-notifications";

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

    const uploads = new s3.Bucket(this, "Uploads", {
      encryption: s3.BucketEncryption.S3_MANAGED,
      blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
      removalPolicy: RemovalPolicy.DESTROY,   // fine for a test stack; use RETAIN in production
      autoDeleteObjects: true,
    });

    const resize = new lambda.Function(this, "Resize", {
      runtime: lambda.Runtime.PYTHON_3_13,
      handler: "index.handler",
      code: lambda.Code.fromAsset("lambda"),
      timeout: Duration.seconds(30),
      memorySize: 512,
    });

    uploads.grantReadWrite(resize);   // writes the IAM policy for you
    uploads.addEventNotification(s3.EventType.OBJECT_CREATED, new s3n.LambdaDestination(resize));

    new CfnOutput(this, "BucketName", { value: uploads.bucketName });
  }
}

The same stack in Python:

from aws_cdk import Stack, RemovalPolicy, Duration, CfnOutput
from aws_cdk import aws_s3 as s3, aws_lambda as _lambda, aws_s3_notifications as s3n
from constructs import Construct

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

        uploads = s3.Bucket(self, "Uploads",
            encryption=s3.BucketEncryption.S3_MANAGED,
            block_public_access=s3.BlockPublicAccess.BLOCK_ALL,
            removal_policy=RemovalPolicy.DESTROY,
            auto_delete_objects=True)

        resize = _lambda.Function(self, "Resize",
            runtime=_lambda.Runtime.PYTHON_3_13,
            handler="index.handler",
            code=_lambda.Code.from_asset("lambda"),
            timeout=Duration.seconds(30),
            memory_size=512)

        uploads.grant_read_write(resize)
        uploads.add_event_notification(s3.EventType.OBJECT_CREATED, s3n.LambdaDestination(resize))
        CfnOutput(self, "BucketName", value=uploads.bucket_name)

Those 25 lines produce a CloudFormation template of well over a hundred lines: the bucket and its policy, the function, its IAM role and policy, the S3 permission to invoke it, the notification configuration and a small helper function that empties the bucket on delete. That gap between what you write and what you get is the main reason teams pick the CDK.

Ethan: "Two days of clicking, versus this file and one command. And the test copy is the same file with a different stack name."

Jake: "So the developer's page of notes becomes the program."

Install the AWS CDK on Windows

The CDK works well on Windows 11 and 10, with a few Windows-specific steps:

  • Node.js: install the LTS version from nodejs.org, or in PowerShell run winget install OpenJS.NodeJS.LTS. Close and reopen your terminal afterwards so the new PATH takes effect, then check with node --version.
  • The CDK CLI: npm install -g aws-cdk, then cdk --version.
  • "cdk.ps1 cannot be loaded because running scripts is disabled on this system": PowerShell's execution policy blocks npm's script wrapper. Run Set-ExecutionPolicy -Scope CurrentUser RemoteSigned once, or call cdk.cmd instead of cdk, or use Command Prompt.
  • AWS CLI: winget install Amazon.AWSCLI, then aws configure sso to sign in.
  • Python projects: after cdk init app --language python, create and activate the virtual environment with py -m venv .venv and .venv\Scripts\activate (the init script's Linux-style source command does not work in PowerShell), then pip install -r requirements.txt.
  • Docker Desktop: needed only if your app builds container images or bundles Lambda code inside Docker (for example Python functions with dependencies). TypeScript Lambda functions can bundle with esbuild instead, without Docker.
  • Long paths and antivirus: if npm install fails with path errors, enable long path support in Windows, and exclude your projects folder from real-time scanning if installs are very slow.

WSL (the Windows Subsystem for Linux) is a good alternative if you prefer Linux tools: install Node.js and the CDK inside your Ubuntu distribution and work from there; everything in this guide works the same.

More AWS CDK examples

A few common building blocks, in TypeScript, to show how little code each one takes. Each line pair below goes inside a stack's constructor:

// A queue with a dead-letter queue, and a Lambda function that reads from it
const dlq = new sqs.Queue(this, "OrdersDlq");
const orders = new sqs.Queue(this, "Orders", { deadLetterQueue: { queue: dlq, maxReceiveCount: 3 } });
worker.addEventSource(new lambdaEventSources.SqsEventSource(orders, { batchSize: 10 }));

// A DynamoDB table, on demand, with point-in-time recovery
const table = new dynamodb.TableV2(this, "Customers", {
  partitionKey: { name: "pk", type: dynamodb.AttributeType.STRING },
  pointInTimeRecoverySpecification: { pointInTimeRecoveryEnabled: true },
});
table.grantReadWriteData(worker);

// A REST API in front of a Lambda function
new apigateway.LambdaRestApi(this, "OrdersApi", { handler: apiFunction });

// A VPC across two Availability Zones with public and private subnets
const vpc = new ec2.Vpc(this, "AppVpc", { maxAzs: 2, natGateways: 1 });

// A customer managed KMS key with rotation
const key = new kms.Key(this, "DataKey", { enableKeyRotation: true });

What each one does for you: the queue example creates two queues and the redrive policy, and addEventSource writes the event source mapping and the permissions the function needs to read from the queue. TableV2 is the current DynamoDB construct, on-demand by default, and the grant gives the function read and write access to that one table only. LambdaRestApi creates an API Gateway REST API with a proxy route and the permission for API Gateway to call your function, as our API Gateway explainer describes. The VPC line creates subnets, route tables, an internet gateway and a NAT gateway; setting natGateways: 1 rather than one per zone saves about $33 a month per gateway in a test environment. The KMS key line creates a key with yearly automatic rotation.

The same bucket in C# and Java looks nearly identical, because all languages share one construct library:

// C#
var uploads = new Bucket(this, "Uploads", new BucketProps {
    Encryption = BucketEncryption.S3_MANAGED,
    BlockPublicAccess = BlockPublicAccess.BLOCK_ALL
});

// Java
Bucket uploads = Bucket.Builder.create(this, "Uploads")
    .encryption(BucketEncryption.S3_MANAGED)
    .blockPublicAccess(BlockPublicAccess.BLOCK_ALL)
    .build();

For full sample projects, the AWS CDK examples repository on GitHub has dozens of working apps in every supported language, from static websites to Fargate services, and the CDK's own source code lives in the aws/aws-cdk repository, where you can read how any construct works or report an issue.

Jake: "So a whole network is one line?"

Ethan: "One line that writes about forty resources. The trick is knowing which line you need, and reading what it made with cdk synth before you trust it."

AWS CDK CLI commands

The commands you will use every day, and the newer ones worth knowing:

  • cdk init: create a new project from a template (app, lib for a construct library, or sample-app) in your chosen language.
  • cdk bootstrap: prepare an account and Region for CDK deployments by deploying the CDKToolkit stack.
  • cdk synth (synthesize): run your app and produce the cloud assembly with a CloudFormation template per stack.
  • cdk diff: show what would change in each stack compared with what is deployed.
  • cdk deploy: deploy one or more stacks; cdk deploy --all deploys every stack, and --require-approval never skips the confirmation prompt in pipelines.
  • cdk destroy: delete one or more stacks.
  • cdk list (ls): list the stacks in your app, which is the first thing to run when a deploy says "No stacks match."
  • cdk watch: watch your project and redeploy on every save, using hotswap for Lambda code and similar changes, for fast development loops (development stacks only).
  • cdk import: bring existing AWS resources under a CDK stack using CloudFormation resource import.
  • cdk migrate: generate a new CDK project from existing AWS resources, a deployed CloudFormation stack or a template, which is how you move a console-built environment like the furniture store's into code.
  • cdk drift: detect resources that have been changed outside the CDK since the last deployment.
  • cdk refactor: keep deployed resources when you move or rename constructs in your code, instead of deleting and recreating them.
  • cdk orphan: safely detach resources from a CloudFormation stack without deleting them.
  • cdk context and cdk flags: manage cached context values and feature flags.
  • cdk doctor: print information about your CDK project and environment, useful when something behaves oddly.
  • cdk publish-assets: upload a stack's assets without deploying it.
  • cdk notices and cdk acknowledge: show and dismiss important notices about the CDK version you use.

Key CDK concepts you will meet

  • App, stacks and environments: an app holds stacks; each stack can be tied to an environment (an account and Region) with env, so the same code can deploy a test stack to one account and a production stack to another.
  • Construct IDs and logical IDs: every construct has an ID unique within its parent. The CDK combines the path of IDs into the CloudFormation logical ID, which is why renaming or moving a construct can replace the resource (and why cdk refactor exists).
  • Removal policies: by default, stateful resources such as buckets and databases are retained when you delete a stack, so you do not lose data by accident. Set RemovalPolicy.DESTROY (and autoDeleteObjects for buckets) only on test stacks.
  • Tokens: values such as a bucket's name are not known until deployment, so the CDK represents them as placeholder tokens during synthesis. Pass the object (bucket) rather than trying to read its name as a string in your code.
  • Context and cdk.json: settings such as feature flags and cached lookups (VPC IDs, availability zones, AMI IDs) live in cdk.json and cdk.context.json. Commit both, so synthesis gives the same result on every machine.
  • Feature flags: new behaviors that would change existing templates arrive behind flags, which new projects turn on automatically and old projects can adopt when ready.
  • Assets: local files and Docker images that the CDK packages and uploads for you, such as Lambda code or a container built from a Dockerfile.
  • Aspects: code that visits every construct in a scope, for example to add tags everywhere or to fail synthesis if any bucket is unencrypted.
  • Escape hatches: when an L2 construct does not expose a property, reach its underlying L1 with node.defaultChild and set the raw CloudFormation property.
  • Cross-stack references: passing a resource from one stack to another creates a CloudFormation export and import, which then blocks changes to that resource while the other stack uses it, the cause of the "export in use" error.

CDK versions: v2, v1 and the CLI

Use CDK v2. It ships as a single library, aws-cdk-lib, containing every stable AWS module, plus the small constructs library; experimental modules come as separate -alpha packages. CDK v1, which used one package per service, reached end of support on June 1, 2023, so any v1 project should be migrated.

The CDK CLI (the aws-cdk npm package you install globally) and the construct library (aws-cdk-lib in your project) are released separately: since early 2025 the CLI has its own version line starting at 2.1000, while the library continues as 2.x. They do not need to match; keep the CLI current, because a newer CLI works with older libraries, while an old CLI may refuse to deploy an app built with a much newer library and ask you to upgrade.

For automation tools and custom deployment scripts, the CDK Toolkit Library exposes the same synth, deploy and destroy operations as a programmatic API, without shelling out to the CLI.

CDK vs CloudFormation, Terraform, SAM and Pulumi

ToolYou writeDeploys throughCloudsBest for
AWS CDKTypeScript, Python, Java, C#, Go, JavaScriptCloudFormationAWSAWS teams who want code, reuse and high-level defaults
CloudFormationYAML or JSON templatesCloudFormationAWSSimple stacks, templates others must read, StackSets
Terraform / OpenTofuHCLProvider APIs, with a state file you storeAWS, Azure, Google Cloud and hundreds of servicesMulti-cloud teams and one tool for everything
AWS SAMYAML with serverless shortcutsCloudFormationAWSSmall serverless apps, local Lambda testing
PulumiTypeScript, Python, Go, C#, Java, YAMLProvider APIs, with managed or self-hosted stateMany cloudsCode-first teams that span several clouds
  • CDK vs CloudFormation: the CDK writes CloudFormation for you. Choose plain CloudFormation for small templates, or when templates must be shared with people who will not run code; choose the CDK when your infrastructure is large, repetitive or shared as reusable components. Our explainer on CloudFormation stacks covers what the CDK deploys into.
  • CDK vs Terraform: both are excellent. Terraform works across clouds and SaaS services with one language and keeps its own state file; the CDK is AWS-only, uses general-purpose languages, and lets CloudFormation hold state and roll back. If you are all-in on AWS and your team writes TypeScript or Python, the CDK; if you manage Azure, Google Cloud, Datadog and Cloudflare too, Terraform.
  • CDK vs SAM: SAM is a lighter YAML layer for serverless apps, with great local testing through the SAM CLI. Many teams start with SAM and move to the CDK as the app grows; you can also use SAM's local testing with CDK-synthesized templates.
  • CDK vs Pulumi: similar idea (real languages), but Pulumi talks to cloud APIs directly and supports many clouds, while the CDK uses CloudFormation and focuses on AWS.

CDK vs the AWS SDK: people mix these up because the names are similar. The SDK (boto3 for Python, the AWS SDK for JavaScript, and so on) is a library your application calls at runtime to use AWS: upload a file, read a table item, send a message. The CDK defines the infrastructure those calls use: it creates the bucket, the table and the queue in the first place. A typical project uses both: the CDK to build the bucket and grant the function access, and the SDK inside the function to put objects in it.

CDK vs the AWS CLI: similarly, the AWS CLI runs one-off commands against your account. You might use it to inspect what the CDK created, but you would not use it to build an environment you need to recreate.

If you are still deciding whether to adopt IaC at all, start with our guide to infrastructure as code on AWS, which covers the broader choice.

Testing and deploying CDK apps with pipelines

Unit tests: the assertions module turns a synthesized stack into a template you can check in ordinary tests (Jest for TypeScript, pytest for Python), so a change that removes encryption or opens a security group fails before review:

import { App } from "aws-cdk-lib";
import { Template } from "aws-cdk-lib/assertions";
import { PhotoAppStack } from "../lib/photo-app-stack";

test("bucket is encrypted and the function exists", () => {
  const template = Template.fromStack(new PhotoAppStack(new App(), "Test"));
  template.hasResourceProperties("AWS::S3::Bucket", {
    BucketEncryption: { ServerSideEncryptionConfiguration: [
      { ServerSideEncryptionByDefault: { SSEAlgorithm: "AES256" } } ] },
  });
  template.resourceCountIs("AWS::Lambda::Function", 2);   // yours + the auto-delete helper
});

Pipelines: the pipelines module (CDK Pipelines) builds a self-updating CodePipeline that synthesizes your app from a Git repository and deploys it stage by stage, for example to a test account, then after approval to production. Many teams use GitHub Actions or another CI service instead, running cdk deploy --require-approval never with short-lived credentials from an OpenID Connect role rather than stored access keys. Either way, deploy from a pipeline, not from laptops, once more than one person changes the infrastructure.

Several environments: instantiate the same stack class more than once with different names and settings, such as new PhotoAppStack(app, "Photo-Test", { env: testEnv }) and new PhotoAppStack(app, "Photo-Prod", { env: prodEnv }), and the test copy that took two days of clicking becomes one more line.

Benefits and limitations of the AWS CDK

Benefits you will notice in the first week:

  • Far less code: L2 constructs and grant methods replace pages of YAML and hand-written IAM policies.
  • Your editor helps you: autocomplete for every resource and property, type checking that catches mistakes before deployment, and inline help.
  • Reuse: wrap your company's standard patterns in constructs and share them as a library, so every team's bucket, alarm and backup setup is the same.
  • Safe changes: cdk diff and CloudFormation change sets show exactly what will happen, and failed deployments roll back automatically.
  • Repeatable environments: test, staging and production from one codebase, with differences expressed as parameters, not as memory.
  • Tests: ordinary unit tests protect the rules you care about.

Limitations to know before you commit:

  • AWS only: the CDK manages AWS resources; for other clouds or SaaS services you need another tool, or CloudFormation's third-party resource types.
  • CloudFormation's limits apply: for example, a stack can hold up to 500 resources, and some changes require replacing a resource. Large apps are split into several stacks.
  • Deployments are as fast as CloudFormation: usually a minute or a few, slower than tools that call APIs directly, though hotswap and watch help during development.
  • Abstraction can hide details: one line can create dozens of resources, including some you did not expect, such as a NAT gateway per Availability Zone. Read cdk synth output and cdk diff until you know what each construct makes.
  • You need a programming language: great for developers, a hurdle for teams who only know YAML.

What teams use the CDK for in practice: serverless APIs (API Gateway, Lambda, DynamoDB), container services on ECS Fargate behind a load balancer, data pipelines (S3, Glue, Step Functions, Batch), static websites (S3 and CloudFront with a certificate), account and network foundations (VPCs, Transit Gateway, IAM roles, logging), and internal platforms where a central team publishes constructs that product teams use to build compliant infrastructure in a few lines.

Ethan: "The CDK won't stop you from building something expensive. It just makes sure you build the same expensive thing every time, which is at least honest."

Custom resources: when CloudFormation cannot do it

Sometimes you need a step that CloudFormation has no resource type for: seeding a database table, calling a third-party API during deployment, or reading a value from another account. CDK custom resources fill that gap. The quickest is AwsCustomResource, which makes a single AWS SDK call when the stack is created, updated or deleted, for example writing a default configuration item into DynamoDB, without you writing a Lambda function. For anything more involved, the Provider framework runs your own Lambda function as the custom resource's handler, with retries and timeouts handled for you. Keep custom resources small and idempotent, because CloudFormation may call them again during updates and rollbacks, and a custom resource that fails on delete can leave a stack stuck.

AWS CDK interview questions (with short answers)

  • What does CDK stand for, and what does it do? Cloud Development Kit; it defines AWS infrastructure in code and deploys it through CloudFormation.
  • What are L1, L2 and L3 constructs? Raw CloudFormation resources, curated resources with defaults and helpers, and multi-resource patterns.
  • What happens during cdk synth? The app runs, builds a construct tree and writes CloudFormation templates and assets to cdk.out.
  • Why do you need cdk bootstrap? To create the S3 bucket, ECR repository and roles the CDK uses to stage assets and deploy.
  • How do you avoid accidentally deleting data? Keep the default retain removal policy on stateful resources, separate stateful and stateless stacks, and review cdk diff for replacements.
  • How do you share infrastructure between stacks? Pass construct objects between stacks (which creates exports and imports), or look values up from SSM parameters to avoid tight coupling.
  • How do you test CDK code? With the assertions module, in normal unit tests, plus cdk-nag for policy checks.
  • What is an escape hatch? Reaching the underlying L1 construct to set a property the L2 does not expose.
  • When would you choose Terraform instead? For multi-cloud or non-AWS services in one tool, or where a team already standardizes on HCL.

A little history: AWS released the CDK as generally available in July 2019, CDK v2 with its single aws-cdk-lib package arrived at the end of 2021, v1 support ended in June 2023, and the CLI moved to its own release line in 2025. It is developed in the open on GitHub, with frequent releases, so new AWS features usually reach the CDK within days or weeks.

Common CDK errors and fixes

  • "SSM parameter /cdk-bootstrap/hnb659fds/version not found" or "This stack uses assets, so the toolkit stack must be deployed": the account and Region are not bootstrapped, or were bootstrapped with a different qualifier. Run cdk bootstrap aws://ACCOUNT/REGION; our bootstrap errors guide covers every variant.
  • "No stacks match the name(s)": the stack name you passed is not the construct ID in your app, or your app did not synthesize. Run cdk list and see our No stacks match guide.
  • "Resource already exists": a resource with a fixed physical name (bucket, role, table) already exists outside the stack. Let the CDK generate names, or import the existing resource with cdk import; see our resource already exists guide.
  • "Export ... cannot be updated as it is in use by ...": a cross-stack reference is blocking a change. Our export in use guide shows the two-step fix.
  • A deploy replaced a database or bucket you renamed: changing a construct's ID changes its logical ID. Use cdk diff before deploying, look for "replace," and use cdk refactor or keep the old ID.
  • Stack stuck in DELETE_FAILED: usually a non-empty bucket or a resource in use; our DELETE_FAILED guide walks through it.
  • "Need to perform AWS calls for account ..., but no credentials have been configured": your shell has no valid AWS credentials or the SSO session expired. Run aws sso login or pass --profile.
  • "Cloud assembly schema version mismatch" or "This CDK CLI is not compatible with the CDK library": your CLI is older than your library. Upgrade with npm install -g aws-cdk, or use npx aws-cdk to run the version pinned in your project.
  • Lookups fail in a pipeline: a context lookup (such as Vpc.fromLookup) needs AWS access at synth time. Commit cdk.context.json so the pipeline reuses cached values.

Best practices

  • Keep stateful and stateless resources in separate stacks, so you can redeploy or replace your application without touching databases and buckets.
  • Let the CDK name resources unless a fixed name is required; generated names avoid collisions between environments.
  • Use L2 constructs and grant methods instead of hand-written IAM policies; they produce least-privilege permissions. Our IAM explainer covers what they generate.
  • Run cdk diff in every pull request, and require review for any "replace" or IAM change.
  • Write unit tests for the rules that matter to you (encryption, public access, retention).
  • Pin the library version in your project and upgrade deliberately, reading the release notes for feature flags.
  • Retain production data: keep the default removal policy on stateful resources in production.
  • Deploy from a pipeline with short-lived credentials once more than one person works on the infrastructure.
  • Avoid console changes to CDK-managed resources; when they happen, find them with cdk drift and move them into code.

Frequently asked questions

What is AWS CDK in simple terms?

A way to describe your AWS infrastructure in a programming language such as TypeScript or Python. The CDK turns your code into a CloudFormation template and deploys it, so the same code always produces the same resources.

Is the AWS CDK free?

Yes. It is free, open-source software. You pay only for the AWS resources it creates, plus cents a month for the bootstrap S3 bucket and ECR repository that hold deployment files.

Which languages does the AWS CDK support?

TypeScript, JavaScript, Python, Java, C# (.NET) and Go. TypeScript gets new features first and has the most examples, but all languages use the same construct library.

What is the difference between CDK and CloudFormation?

CloudFormation is the AWS service that deploys templates. The CDK is a tool that generates those templates from code and then uses CloudFormation to deploy them. You write far less with the CDK, and CloudFormation still handles change sets and rollback.

Is the CDK better than Terraform?

Neither is better for everyone. The CDK suits AWS-only teams who like general-purpose languages and want CloudFormation to manage state. Terraform suits teams managing several clouds and services with one tool and one language.

What does cdk bootstrap do?

It prepares an AWS account and Region for CDK deployments by creating the CDKToolkit stack: an S3 bucket and an ECR repository for assets, and IAM roles the CDK uses to deploy. Run it once per account and Region.

What does cdk synth do?

It runs your CDK app and produces the cloud assembly in cdk.out: a CloudFormation template for each stack plus the assets they reference. It does not deploy anything.

What is a construct in CDK?

A building block that represents one or more AWS resources. L1 constructs map directly to CloudFormation resources, L2 constructs add defaults and helper methods, and L3 constructs wire several resources into a common pattern.

What is the difference between CDK v1 and v2?

CDK v2 packages every stable module in one library, aws-cdk-lib, and is the only supported version. CDK v1, with one package per service, reached end of support on June 1, 2023.

Do I need Node.js to use the CDK with Python?

Yes. The CDK CLI is a Node.js program, so you install Node.js and the aws-cdk package even when your app is written in Python, Java, C# or Go.

How do I install the AWS CDK?

Install a current LTS version of Node.js, run npm install -g aws-cdk, and check it with cdk --version. Then configure AWS credentials and create a project with cdk init app --language typescript or python.

Can I convert existing resources to CDK?

Yes. cdk migrate generates a new CDK project from existing resources, a deployed CloudFormation stack or a template, and cdk import brings existing resources into an existing stack.

What is CDK drift?

Changes made to CDK-managed resources outside the CDK, for example in the console. cdk drift detects them, so you can either undo them or add them to your code.

How do I delete everything a CDK app created?

Run cdk destroy for each stack, or cdk destroy --all. Resources with a retain removal policy, such as buckets and databases by default, stay behind and must be deleted separately.

What is CDK Pipelines?

A CDK module that builds a self-updating CodePipeline which synthesizes your app from source control and deploys it through stages such as test and production, with approvals between them.

How do I test CDK code?

Use the assertions module to synthesize a stack into a template inside a normal unit test, then check resource counts and properties with methods such as hasResourceProperties and resourceCountIs.

Why did my CDK deploy replace a resource?

Its logical ID changed, usually because you renamed or moved its construct, or you changed a property that cannot be updated in place. Run cdk diff before deploying to spot replacements, and use cdk refactor when you reorganize code.

What is the full form of AWS CDK?

AWS Cloud Development Kit. "Cloud Development Kit" describes what it is: a set of libraries and a command-line tool for developing your cloud infrastructure as code.

Does the AWS CDK use CloudFormation?

Yes. Every CDK deployment synthesizes CloudFormation templates and deploys them as CloudFormation stacks, so you can see your CDK stacks, events and resources in the CloudFormation console.

Is the AWS CDK on GitHub?

Yes. The CDK is open source and developed in the aws/aws-cdk repository on GitHub, and AWS also publishes a CDK examples repository with sample apps in every supported language.

How do I install the AWS CDK on Windows?

Install Node.js LTS (for example with winget install OpenJS.NodeJS.LTS), open a new terminal, run npm install -g aws-cdk and check cdk --version. If PowerShell blocks cdk.ps1, run Set-ExecutionPolicy -Scope CurrentUser RemoteSigned or use cdk.cmd.

What is the difference between the CDK and the AWS SDK?

The CDK creates your infrastructure, such as buckets, tables and queues. The SDK is a library your application uses at runtime to work with that infrastructure, such as uploading a file or reading an item.

What is the AWS CDK used for?

Building AWS environments you can recreate exactly: serverless APIs, container services, data pipelines, static websites, networks and account foundations, and reusable company patterns shared as construct libraries.

How long does a CDK deployment take?

As long as CloudFormation needs to create or change the resources, usually from under a minute for small changes to tens of minutes for resources such as databases or CloudFront distributions. cdk watch with hotswap speeds up Lambda code changes during development.

Which language should I use with the AWS CDK?

The one your team already writes. TypeScript has the most examples and gets features first; Python is the most popular choice for data and operations teams; Java and C# suit teams already in those ecosystems.

Can I use the CDK with an existing CloudFormation template?

Yes. Include it in a CDK stack with the CfnInclude construct, which lets you keep the template as it is and gradually reference or replace its resources with CDK constructs, or convert it fully with cdk migrate.

What is the CDK CLI version 2.1000?

Since early 2025 the CDK CLI is versioned separately from the construct library, starting at 2.1000. Your CLI and aws-cdk-lib versions do not need to match; keep the CLI up to date.

For readers preparing for an AWS certification

We have been covering AWS certifications alongside our fixes, so here is a short extra for readers studying for one. If you only came for the fix, you already have it; feel free to skip this part.

Exams that test this topic: Developer – Associate (DVA-C03 from December 1, 2026) • Solutions Architect – Associate (SAA-C03) • DevOps Engineer – Professional (DOP-C02).

Here are the exam-style questions this topic tends to raise, with the reasoning you need to answer them:

1. A team wants to define AWS infrastructure in TypeScript and deploy it through CloudFormation. Which tool fits?

The AWS Cloud Development Kit (CDK).

2. A first CDK deployment fails because the SSM parameter /cdk-bootstrap/hnb659fds/version is not found. What fixes it?

Run cdk bootstrap for that account and Region to create the CDKToolkit stack.

3. Which CDK command shows the changes a deployment would make, before deploying?

cdk diff.

4. Which construct level provides secure defaults and helper methods such as grantRead?

L2 constructs.

5. A database defined in CDK must survive if its stack is deleted. Which setting ensures this?

A RETAIN removal policy (the default for stateful resources).

6. A CDK app must deploy automatically to test and then production accounts from a Git repository. Which CDK feature fits?

CDK Pipelines (the pipelines module), which builds a self-updating CodePipeline.

7. Existing resources created in the console must be brought under a CDK stack without recreating them. Which command helps?

cdk import (or cdk migrate to generate a new CDK project from existing resources).

Exam codes and dates change often. Our AWS certification changes page keeps track of what is current.

πŸ“š ALSO READ

Where to go next, from bootstrap errors to DELETE_FAILED fixes:

📌 Bookmark this; the tutorial, the CLI table and the error fixes are the parts you will come back for.

The developer spent a week moving the store's environment into a CDK app, starting with cdk migrate on the production stack and then tidying the generated code into three stacks: data, application and the render pipeline. The test copy now takes eleven minutes to create and is identical to production down to the alarm thresholds. The first time someone changed a bucket setting in the console, cdk drift flagged it the same afternoon. Jake asked whether the CDK could also set up the printer. It could not.

📌 If you keep one line from this page

The AWS CDK is free, open-source infrastructure as code: you write TypeScript, Python, Java, C#, Go or JavaScript with high-level constructs, cdk synth turns it into CloudFormation, and cdk deploy creates the same resources every time; bootstrap each account and Region once.

cdk diff before every deploy · retain production data · keep the CLI current.

Revision note. Written October 21, 2026. We will update this page when the CDK CLI, construct library or recommended practices change.

Related