Provisioning infrastructure in the Cloud using code has been a best practice standard for years. Organizations now see the clear benefits of defining AWS resources programmatically compared to the manual approach in the AWS Console.
For a long time, two popular tools dominated the Infrastructure as Code landscape: AWS CloudFormation and Terraform. Both use a declarative approach where you define your desired end state in JSON, YAML, or HCL configuration files.
However, the configuration of a declarative approach can be rather extensive. Large templates with thousands of lines need to be maintained, and you miss out on the power of programming languages like loops, conditionals, and object-oriented patterns.
That's where AWS CDK comes in. It lets you define Cloud infrastructure using familiar programming languages, bringing software development best practices to infrastructure management.
In this guide, you'll learn what AWS CDK is, its core concepts, when you should (and shouldn't) use it, and how to get started building your first CDK application.
What is the AWS Cloud Development Kit (CDK)?
The AWS Cloud Development Kit (CDK) is an open-source software development framework that allows you to define and provision Cloud infrastructure in code and deploy it through AWS CloudFormation.
AWS publicly released AWS CDK (v0.8.0) in beta back in 2018 as an alternative approach to developing AWS resources programmatically using TypeScript.

First public beta release of AWS CDK
AWS made this project open-source, enabling the community to contribute code and pass feedback directly to the official maintainers. In December 2021 during re:Invent, Werner Vogels announced that AWS CDK v2 became generally available (GA), which is the current stable version actively developed today. CDK v1 reached end of support in June 2023.
Supported Programming Languages
AWS CDK supports six programming languages, allowing you to use your existing skills:
- TypeScript
- JavaScript
- Python
- Java
- C#/.NET
- Go
You can use any of these languages to define reusable cloud components (constructs), compose them into stacks and apps, and deploy through AWS CloudFormation.
How AWS CDK Works
Understanding how CDK transforms your code into deployed infrastructure is essential. The process involves four main phases:
1. Development Phase: You write CDK code in your preferred language, defining infrastructure using constructs from the AWS Construct Library.
2. Synthesis Phase: The cdk synth command compiles your CDK application into AWS CloudFormation templates. This executes your CDK app code, generates a CloudFormation template in JSON format for each stack, and saves templates to the cdk.out directory (called the cloud assembly).
3. Bootstrapping (One-time): Before your first deployment, each AWS environment (account + region) must be bootstrapped. This creates resources CDK needs: an S3 bucket for file assets, an ECR repository for Docker images, IAM roles with deployment permissions, and an SSM parameter for version tracking.
4. Deployment Phase: The cdk deploy command uploads assets to the bootstrapped resources, submits the CloudFormation template, and CloudFormation provisions your AWS resources.
Core Concepts: Constructs, Stacks, and Apps
AWS CDK is built on three fundamental building blocks that work together hierarchically. Understanding these concepts is crucial for building well-structured CDK applications.

AWS CDK Concept architecture diagram
The Three Levels of Constructs
Constructs are the basic building blocks of CDK applications. A construct represents one or more AWS CloudFormation resources and their configuration. CDK organizes constructs into three levels, each offering different degrees of abstraction:
L1 Constructs (CFN Resources) are the lowest-level constructs offering no abstraction. Each L1 construct maps directly to a single CloudFormation resource, named with a Cfn prefix (e.g., CfnBucket for S3 buckets). They're auto-generated from the CloudFormation specification and provide complete control over all resource properties. Use L1 constructs when you need properties that L2/L3 constructs don't expose, using escape hatches.
L2 Constructs (Curated) are thoughtfully developed by the CDK team and are the most widely used construct type. They provide intuitive, intent-based APIs with sensible default property configurations and implement best practice security policies automatically. For example, the s3.Bucket class creates an encrypted bucket by default. L2 constructs are your go-to choice for most resources.
L3 Constructs (Patterns) are the highest level of abstraction. They contain collections of resources configured to work together for specific use cases. A single L3 construct like ApplicationLoadBalancedFargateService creates an entire ECS cluster, Fargate service, application load balancer, security groups, and IAM roles with just a few lines of code.
Stacks
A CDK Stack represents a collection of AWS resources defined using CDK constructs. When deployed, resources within a stack are deployed together as an AWS CloudFormation stack.
Key characteristics:
- A stack is the unit of deployment; everything in a stack deploys together
- Each stack maps to a single CloudFormation stack
- Organize related resources into logical units (API stack, database stack, monitoring stack) based on deployment boundaries
- Stateful resources like databases should often be in separate stacks from stateless resources for safer management
Apps and Composition
A CDK App is the top-level construct that serves as a container for one or more stacks. When you synthesize an app, it generates CloudFormation templates for all stacks defined within it. The cloud assembly output can then be deployed to AWS.
Composition is the key pattern for building higher-level abstractions. You create custom constructs by combining lower-level constructs, enabling code reuse and organizational standards. This is how you build your own L3 patterns tailored to your organization's needs.
Should You Use AWS CDK?
CDK is powerful, but it's not the right choice for every situation. Here's a framework to help you decide.
When to Use AWS CDK
CDK shines in these scenarios:
- Multi-service applications: Building apps that combine multiple AWS services (API Gateway + Lambda + DynamoDB, ECS + RDS + ElastiCache)
- Reusable infrastructure patterns: Organizations wanting to standardize patterns across teams through shared construct libraries
- Complex logic requirements: When infrastructure needs conditional logic, loops, or computations that are cumbersome in templates
- Developer-centric teams: Teams with strong programming backgrounds who prefer code over configuration files
- CI/CD automation: Automated deployment pipelines where infrastructure is part of application code
- Testing requirements: When infrastructure needs unit testing and validation before deployment
- Multi-environment deployments: Deploying the same infrastructure to dev/test/prod with different configurations
When NOT to Use AWS CDK
Consider alternatives in these situations:
- Very simple deployments: Single resources or straightforward infrastructure might not justify CDK's overhead
- Teams unfamiliar with programming: If your team prefers templates and isn't comfortable with TypeScript/Python, CloudFormation may be more practical
- Multi-cloud requirements: CDK is AWS-only. For workloads spanning multiple cloud providers, consider Terraform
- Organizations standardized on other tools: If your company has already invested heavily in Terraform or another IaC tool, switching has costs
AWS CDK vs CloudFormation vs Terraform
Understanding how CDK compares to other IaC tools helps you make informed decisions.
CDK vs CloudFormation
CDK generates CloudFormation templates under the hood, so they share the same deployment engine. The key differences are in the developer experience:
| Aspect | CloudFormation | AWS CDK |
|---|---|---|
| Definition format | JSON or YAML templates | Programming languages |
| Abstraction level | Low-level resource definitions | L1, L2, L3 construct abstractions |
| Code reusability | Limited (nested stacks, modules) | Extensive (classes, modules, packages) |
| Boilerplate | Must define all properties | Sensible defaults provided |
| Logic | Limited conditions, intrinsic functions | Full programming language capabilities |
| Testing | Limited | Unit tests, snapshot tests, assertions |
| IDE support | Basic YAML/JSON support | Full IDE features (autocomplete, type checking) |
From my own experience as a DevOps engineer having used both services extensively, I prefer AWS CDK for:
- Speed: L2/L3 constructs with sensible defaults and best practice security policies
- Flexibility: Using a programming language to define infrastructure instead of YAML/JSON
- Career value: Programming skills are more transferable than CloudFormation-specific syntax
One community member made a good point about setting expectations:
"1500 lines of CloudFormation became 14 lines of CDK" It's important to understand that the deployed application still has 1500 lines' worth of operations and maintenance ownership, not 14
— Ben Kehoe (@ben11kehoe) December 2, 2021
CDK is a transpiler for CloudFormation. Understanding CloudFormation concepts remains valuable because that's what actually runs your deployments. Validate synthesized templates with tools like cfn-lint and checkov to prevent misconfigurations.
CDK vs Terraform
Both CDK and Terraform are excellent IaC tools with different strengths. For a comprehensive comparison covering multi-cloud support, state management, learning curves, and migration paths, see our dedicated AWS CDK vs Terraform guide.
Quick summary: Choose CDK for AWS-focused development with programming language benefits. Choose Terraform for multi-cloud or if your team is already proficient with HCL.
Benefits and Features of AWS CDK
CDK brings software development practices to infrastructure management. Here are the key advantages organized by category.
Infrastructure as Code Benefits
CDK enables treating infrastructure the same way developers treat application code:
- Version control: Track infrastructure changes with Git, review PRs for infrastructure modifications
- Code reviews: Apply the same rigor to infrastructure changes as application code
- Unit testing: Write tests to validate your infrastructure before deployment
- Refactoring: Restructure and improve infrastructure code with confidence
Use Familiar Programming Languages
Unlike template-based approaches, CDK lets you use real programming languages:
- Leverage existing team expertise in TypeScript, Python, Java, C#, or Go
- Use conditionals, loops, and object-oriented patterns
- Get full IDE support: syntax highlighting, code completion, inline documentation, refactoring tools
- Use the same language for infrastructure and application logic
- Apply software engineering best practices (DRY, SOLID principles)
Rapid Development with Constructs
CDK accelerates development through its construct model:
- Reduce boilerplate: L2 constructs handle common configurations automatically
- Secure defaults: Best practice security policies built into constructs
- Reusable components: Share constructs across teams via Construct Hub
- Organizational standards: Create custom L3 patterns that enforce your company's requirements
- Store everything together: Infrastructure, application code, config, and deployment in a single repo
CloudFormation Integration
CDK leverages AWS CloudFormation for deployments:
- Predictable deployments: CloudFormation's proven deployment engine
- Automatic rollback: Failed deployments roll back automatically
- Full AWS support: Access to all CloudFormation-supported resources
- Familiar tools: Use existing CloudFormation monitoring and troubleshooting knowledge
Real-World Use Cases and Examples
Let's look at practical examples of CDK in action.
Serverless API Example
Here's a simple S3 bucket with versioning enabled:
import * as s3 from 'aws-cdk-lib/aws-s3';
new s3.Bucket(this, 'MyFirstBucket', {
versioned: true,
encryption: s3.BucketEncryption.S3_MANAGED
});
For a complete walkthrough, see our guide on setting up an S3 bucket with AWS CDK. You can also learn how to assign IAM roles to Lambda functions for building secure serverless APIs.
Container Workloads
L3 patterns shine when deploying container workloads. This example creates a complete Fargate service with load balancer:
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import * as ecs from 'aws-cdk-lib/aws-ecs';
import * as ecs_patterns from 'aws-cdk-lib/aws-ecs-patterns';
const vpc = new ec2.Vpc(this, "MyVpc", {
maxAzs: 3
});
const cluster = new ecs.Cluster(this, "MyCluster", {
vpc: vpc
});
new ecs_patterns.ApplicationLoadBalancedFargateService(this, "MyFargateService", {
cluster: cluster,
cpu: 512,
desiredCount: 6,
taskImageOptions: {
image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample")
},
memoryLimitMiB: 2048,
publicLoadBalancer: true
});
This single L3 pattern creates:
- VPC with 3 availability zones
- ECS cluster
- Fargate service with 6 tasks
- Application load balancer
- Security groups
- IAM roles
- All necessary networking
For detailed walkthroughs, see our Application Load Balanced Fargate Service and Scheduled Fargate Task tutorials.
Multi-Environment Deployments
CDK makes deploying to multiple environments straightforward. Use CDK context or environment variables to configure differences between dev, test, and production:
const app = new cdk.App();
new MyStack(app, 'Dev', {
env: { account: '111111111111', region: 'us-east-1' },
instanceSize: 'small'
});
new MyStack(app, 'Prod', {
env: { account: '222222222222', region: 'us-east-1' },
instanceSize: 'large'
});
Learn how to share resources across stacks for more complex multi-stack architectures. For fundamentals on how stacks work, see our complete guide to CDK stacks.
Getting Started with AWS CDK
Ready to try CDK? Here's how to get started.
Prerequisites and Installation
To install the AWS CDK toolkit on your machine, use the node package manager:
npm install -g aws-cdk
added 180 packages, and audited 181 packages in 7s
found 0 vulnerabilities
You'll also need:
- Node.js (for all CDK languages, as the CLI is built on Node)
- AWS CLI configured with credentials
- Your preferred language runtime (Python, Java, .NET, or Go if not using TypeScript/JavaScript)
Bootstrapping Your AWS Environment
Before your first deployment, you must bootstrap your AWS environment. This one-time setup per account+region creates resources CDK needs for deployments:
cdk bootstrap aws://ACCOUNT-NUMBER/REGION
This creates:
- S3 bucket: Stores file assets (Lambda code, CloudFormation templates, static content)
- ECR repository: Stores Docker image assets
- IAM roles: Permissions for CDK deployments
- SSM parameter: Tracks bootstrap stack version
Important: Attempting to deploy without bootstrapping results in an error: "SSM parameter /cdk-bootstrap/hnb659fds/version not found"
Your First CDK Application
Create a new CDK project:
mkdir my-cdk-app && cd my-cdk-app
cdk init app --language typescript
This scaffolds a complete CDK project. Edit lib/my-cdk-app-stack.ts to add your resources, then:
cdk synth # Generate CloudFormation template
cdk diff # Preview changes before deploying
cdk deploy # Deploy to AWS
For organizing larger projects, see our guide on optimizing your CDK project structure.
Production-Ready Starter Kit
Want to skip the boilerplate and start with production-ready defaults? Check out the AWS CDK Starter Kit - a TypeScript template with secure OIDC authentication, automated CI/CD, and branch-based deployments.
This starter kit was born from real-world experience. After copy-pasting the same boilerplate code across multiple client projects, I refined it into a reusable template that includes best practices, an optimized project structure, and a secure GitHub Actions pipeline using OIDC for temporary credentials.
For setup instructions and configuration options, see the AWS CDK Starter Kit documentation.
CDK Ecosystem and Resources
The CDK ecosystem extends beyond the core library.
Construct Hub
Construct Hub is an online registry for finding, publishing, and sharing CDK constructs. It includes:
- AWS-authored constructs from the AWS Construct Library
- AWS Partner Network (APN) partner constructs
- Community open-source constructs
Before building something from scratch, check Construct Hub for existing solutions. You can also publish your own constructs for others to use.
Developer Tools
These tools improve your CDK development workflow:
- AWS Toolkit for VS Code: Gain tree view access to your CDK App within VS Code
- Visual Studio IntelliCode: AI-assisted code completion when building constructs
- cdk-nag: Checks your application for best practices based on rules like AWS Solutions, HIPAA, and NIST. Integrate into CI/CD pipelines to enforce standards
- Autocomplete CDK constructs: Speed up development with CDK Construct Snippets extension
- ESLint/Prettier: Standard code quality tools work great with CDK TypeScript projects
AWS CDK Best Practices
These best practices will help you build maintainable, production-ready CDK applications:
| Best Practice | Description |
|---|---|
| Model with constructs, deploy with stacks | Use constructs for building logical units. Stacks are only for deployment grouping. |
| Make decisions at synthesis time | Use programming language logic (if statements, loops) rather than CloudFormation conditions and parameters. This keeps templates simple and behavior predictable. |
| Separate stateful and stateless resources | Keep databases and storage in separate stacks from APIs and compute. Enable termination protection on stateful stacks. |
| Use high-level constructs | Prefer L2/L3 constructs for faster development with secure defaults. Drop to L1 only when higher-level constructs lack needed properties. |
Use cdk diff before deploying | Always review changes before applying them to production. This catches unintended modifications. |
| Write tests for critical infrastructure | Use fine-grained assertions for security-critical resources. Snapshot tests help catch accidental changes during refactoring. |
| Implement a landing zone strategy | Organize AWS accounts and automate security policies. See our CDK Landing Zone versus Control Tower alternatives comparison. |
For more best practices, check the official documentation and our guide on AWS multi-account best practices.
Troubleshooting Common CDK Issues
One of the more common errors when running AWS CDK commands:
--app is required either in command-line, in cdk.json or in ~/.cdk.json
This error occurs when you run CDK commands outside your project's root directory.
To fix: Run commands like cdk init, cdk synth, or cdk deploy from the directory containing cdk.json. This file lives in the main directory of your CDK project alongside your main entry point.
For more solutions, see the official troubleshooting guide from AWS.
Dive Deeper into AWS CDK
I've written more articles on AWS CDK where we dive deeper into building constructs, using best practices, and much more:
Designing a Multi-Principal IAM Role using AWS CDK
Learn how to create an IAM role that utilizes multiple principals using the AWS CDK.
Create a DependsOn relation between resources in AWS CDK
How to establish a "DependsOn" relationship between resources like RDS and EC2 instances.
Assign a Custom Role to a Lambda Function with AWS CDK
Create a custom IAM role, an AWS Lambda function, and assign the custom role to the function.
Optimize your AWS CDK Project Structure for Growth
An optimized AWS CDK project structure with explanations of the design decisions.
How to set up an Amazon S3 Bucket using AWS CDK
Steps to set up and configure an Amazon S3 Bucket using AWS CDK in TypeScript.
Conclusion
AWS CDK brings the power of programming languages to infrastructure management. You've learned what CDK is, its core concepts (constructs, stacks, apps), and how it compares to CloudFormation and Terraform.
The decision framework should help you evaluate whether CDK is right for your situation. For AWS-focused teams with programming experience who need reusable patterns and testing capabilities, CDK is an excellent choice.
Ready to start? Install the CDK toolkit, bootstrap your AWS environment, and create your first CDK app. Check out our AWS CDK examples for practical tutorials.
What's your experience with AWS CDK? Have questions about specific use cases? Let me know in the comments below.
AWS CDK FAQ
What is the difference between AWS SDK and AWS CDK?
Is AWS CDK better than Terraform?
How much does AWS CDK cost?
Can I convert existing CloudFormation templates to CDK?
How long does it take to learn AWS CDK?
Does AWS CDK support all AWS services?
Can I use CDK alongside existing CloudFormation stacks?
Build Scalable CDK Apps That Are Easy to Maintain
Transform your complex CDK codebase into a structured, reusable architecture. Get real-world expertise from someone who's built production CDK at scale.

![What is an AWS CDK Stack? Complete Guide with Examples [2026]](/_next/image?url=%2Fimages%2Fblog%2Faws-cdk-stack%2Faws-cdk-stack.webp&w=3840&q=70)

![What is an AWS CDK Construct? Complete Guide to L1, L2, and L3 [2026]](/_next/image?url=%2Fimages%2Fblog%2Faws-cdk-construct%2Faws-cdk-construct.webp&w=3840&q=70)