If you're a software developer managing AWS-only infrastructure, AWS CDK will almost certainly make you more productive than Terraform. If you're a platform engineer managing multi-cloud or working alongside an ops-heavy team, Terraform is probably the right call.
That's the short answer to AWS CDK vs Terraform. But an infrastructure as code tool is a choice you live with for years, and two things have shifted the decision since 2025. HashiCorp sunset CDK for Terraform (CDKTF) in December 2025, removing the "programming languages on Terraform's engine" option. And AWS shipped a run of CDK and CloudFormation changes (Toolkit Library, Refactor, Mixins, and, in 2026, faster default deployments) that change how CDK feels day to day.
You'll get a recommendation by team type, the mechanics behind deploy speed, side-by-side code that shows the real abstraction difference, migration paths in both directions, and a straight answer on CDKTF.
Through Towards The Cloud I build and review AWS CDK codebases for clients, so read this knowing where I lean. I've given Terraform the same scrutiny and used HashiCorp's own documentation for its side.
Executive Summary: Which Tool Should You Choose?
Two questions decide this faster than any feature list: does your infrastructure live only on AWS, and who writes the infrastructure code every day?
Quick Recommendation Matrix
Choose AWS CDK if:
- Your infrastructure is 100% AWS
- Your team are developers who prefer TypeScript, Python, Java, C#, or Go
- You want sensible defaults and high-level abstractions (L2/L3 constructs)
- You don't need multi-cloud support now or in the foreseeable future
Choose Terraform if:
- You need multi-cloud support (AWS, Azure, GCP) or manage SaaS resources
- You prefer declarative configuration over programming
- You have existing Terraform expertise and modules
- Your ops team (not developers) manages infrastructure
Consider both if CDK handles application infrastructure while Terraform manages foundational or multi-cloud resources. Only go hybrid for a specific reason.
TL;DR: Key Takeaways
- Neither is "better": they're optimized for different teams and scopes
- CDK = AWS-native programming with CloudFormation-managed state, L2/L3 abstractions, and an active 2025-2026 feature set
- Terraform = multi-cloud declarative with state you configure yourself, thousands of providers, and a Business Source License since version 1.6.0
- CDK for Terraform (CDKTF) is gone: HashiCorp archived it on December 10, 2025
- CDK deploys through CloudFormation, which waits for each resource to stabilize. That can make it slower than Terraform for some changes, and AWS sped up CloudFormation's defaults in 2026
- Hybrid is valid but complex: use it only with clear team and resource boundaries
The Quick Comparison Table
One architectural difference drives most rows: CDK deploys through CloudFormation, Terraform calls provider APIs directly.
| Feature | AWS CDK | Terraform |
|---|---|---|
| Languages | TypeScript, JavaScript, Python, Java, C#, Go | HCL (HashiCorp Configuration Language) |
| Cloud Support | AWS only | Multi-cloud and SaaS (thousands of providers) |
| State Management | Managed by CloudFormation | You configure a backend (usually S3 on AWS) |
| Deployment Engine | CloudFormation | Terraform core calling provider APIs directly |
| Rollback | Automatic on failure (default mode) | None; fix forward and re-apply |
| Testing | aws-cdk-lib/assertions in your test runner | Built-in terraform test (1.6+), plus Terratest |
| Setup Required | cdk bootstrap per account/Region | Backend configuration per project |
| Abstractions | L1, L2, L3 constructs plus Mixins | Resources and modules |
| Version (Nov 2026) | aws-cdk-lib 2.275.0, CLI 2.1148.0 | Terraform 1.17.1 |
| Licensing | Apache 2.0 | BSL 1.1 for 1.6.0 and later |
| Learning Curve (Devs) | Low (familiar languages) | Medium (learn HCL) |
| Learning Curve (Ops) | Medium (requires programming) | Low (declarative config) |
| Drift Detection | cdk drift (CloudFormation drift detection) | terraform plan or terraform plan -refresh-only |
Why these differences matter: CDK generates CloudFormation templates and hands them to AWS's deployment engine. Terraform calls AWS APIs directly through its provider. That one architectural difference drives provisioning speed, rollback behavior, where state lives, and how you debug a failed deploy.
Understanding the Fundamentals
Both tools are Infrastructure as Code, but they start from different ends. CDK is a code generator in front of an AWS service. Terraform is a standalone engine with its own state.
What is AWS CDK?
AWS CDK (Cloud Development Kit) is an open-source framework for defining cloud infrastructure in general-purpose programming languages. Your code is synthesized into CloudFormation templates, which CloudFormation then deploys.
Key characteristics:
- Six languages: TypeScript, JavaScript, Python, Java, C#, and Go
- A layer on top of CloudFormation, not a replacement for it
- Three levels of constructs, plus CDK Mixins (GA March 2026) for cross-cutting features
- Two version numbers: since February 2025, the CLI (
aws-cdk, 2.1148.0 at the time of writing) and the Construct Library (aws-cdk-lib, 2.275.0) release independently. Treat the library version as "the" CDK version and keep the CLI release date at or after the library's
The construct model is the heart of CDK:
- L1 (CFN Resources): 1:1 mapping to CloudFormation resources (e.g.,
CfnBucket). Complete control, no abstraction - L2 (Curated Constructs): opinionated resources with sensible defaults (e.g.,
s3.Bucket). The ones you'll use most - L3 (Patterns): multi-resource architectures in one construct (e.g.,
ApplicationLoadBalancedFargateService) - Mixins: features such as versioning or blocked public access, applied to L1 or L2 constructs via
.with()
What is Terraform?
Terraform is a platform-agnostic IaC tool from HashiCorp (part of IBM since February 2025) that uses HashiCorp Configuration Language (HCL). It runs its own deployment engine and records what it created in a state file.
Key characteristics:
- HCL: a declarative configuration language designed to be human-readable
- Platform-agnostic: thousands of providers cover AWS, Azure, GCP, Kubernetes, and SaaS tools
- State files: JSON records of your deployed infrastructure, which is how Terraform knows what exists
- Own engine: Terraform calls cloud APIs directly, not through CloudFormation
The workflow is terraform init (download providers), terraform plan (preview), terraform apply (provision or update), and terraform destroy (remove everything it manages).
The Imperative vs Declarative Paradigm
CDK is imperative: you build up infrastructure with loops, conditionals, and functions. The output is still a declarative CloudFormation template, but you get there with a full programming language.
Terraform is declarative: you describe WHAT should exist, and the engine works out how to get there.
Here's the difference with a simple S3 bucket:
// CDK (TypeScript) - imperative approach
import * as s3 from 'aws-cdk-lib/aws-s3';
import * as cdk from 'aws-cdk-lib';
const bucket = new s3.Bucket(this, 'MyBucket', {
encryption: s3.BucketEncryption.S3_MANAGED,
versioned: true,
removalPolicy: cdk.RemovalPolicy.RETAIN
});
# Terraform (HCL) - declarative approach
resource "aws_s3_bucket" "my_bucket" {
bucket = "my-unique-bucket-name"
}
resource "aws_s3_bucket_versioning" "my_bucket" {
bucket = aws_s3_bucket.my_bucket.id
versioning_configuration {
status = "Enabled"
}
}
resource "aws_s3_bucket_server_side_encryption_configuration" "my_bucket" {
bucket = aws_s3_bucket.my_bucket.id
rule {
apply_server_side_encryption_by_default {
sse_algorithm = "AES256"
}
}
}
CDK's L2 construct handles encryption and versioning as properties, while Terraform needs separate resource blocks. That's the abstraction benefit, and also its cost: you see less of what's being created.
CDK vs Terraform vs Pulumi: The Third Option
With CDKTF gone, Pulumi is the main remaining option for writing multi-cloud infrastructure in general-purpose languages. It isn't the right default for an AWS-only team, but it belongs in the decision if you need both programming languages and more than one cloud.
Where Pulumi Fits
Pulumi supports TypeScript, JavaScript, Python, Go, .NET, Java, YAML, and HCL, and AWS Prescriptive Guidance describes it as covering more than fifty cloud and SaaS providers. State lives in Pulumi Cloud or a self-managed backend, and the project is open source under Apache 2.0. The trade-off is community size: Terraform has far more public modules and answered questions, so with Pulumi you'll more often be first to hit a problem.
Two AWS-native options sit on the other side. If you'd rather write YAML or JSON templates with no programming layer, plain CloudFormation is still valid; I compare the two in AWS CDK vs CloudFormation. For a purely serverless application, AWS SAM's simplified templates may be all you need.
When to Consider Each
- AWS-only and your team writes code: CDK
- Multi-cloud and your team writes code: evaluate Pulumi
- Multi-cloud and your team prefers declarative config: Terraform
- Mixed team with no clear IaC owner: Terraform's HCL is the neutral middle ground
What Changed in 2025-2026: CDK's New Features
If your picture of CDK dates from before 2025, these changes alter the comparison. Most target long-standing complaints: refactors that replace resources, CLI-only automation, and slow CloudFormation deploys.
| Date | Feature | What It Solves |
|---|---|---|
| February 2025 | CLI/Construct Library version split | CLI and library release independently |
| May 2025 | CDK Toolkit Library (GA) | Programmatic CDK operations without CLI subprocesses |
| September 2025 | CDK Refactor (Preview) | Rename or move constructs without resource replacement |
| March 2026 | CDK Mixins (GA) | Add features to any construct via .with() |
| May 2026 | Fn::GetStackOutput | Cross-account and cross-Region references, used by CDK automatically |
| June 2026 | CloudFormation express mode | cdk deploy --express for faster development deploys |
| 2026 | Faster default deployments | Default mode moves on as soon as each resource is ready |
CDK Toolkit Library: Programmatic CDK Without CLI Subprocesses
The CDK Toolkit Library (@aws-cdk/toolkit-lib) exposes synth, deploy, and destroy as library calls:
npm install --save @aws-cdk/toolkit-lib
If you build custom CI/CD workflows, platform tooling, or ephemeral environment managers, your code calls the library instead of shelling out to cdk deploy, and it can inspect the synthesized template and enforce guardrails before anything deploys.
CDK Refactor: Safe Code Restructuring Without Resource Replacement
Renaming a construct or moving it to another stack changes its logical ID, and CloudFormation treats a new logical ID as a new resource: create the new one, delete the old one. For a database or a bucket full of data, that's a production incident.
cdk refactor detects moved or renamed resources and uses CloudFormation's refactoring API to update logical IDs while keeping the physical resources. It's still in preview, so you run it with --unstable=refactor; --dry-run shows the mapping first. It refuses to run if your app also adds, deletes, or modifies resources, so ship the refactor as its own deployment.
CDK Mixins: Cross-Cutting Features Without Subclassing
CDK Mixins apply the same settings (versioning, auto-delete, blocked public access) to many constructs without an inheritance hierarchy or raw property overrides:
import * as s3 from 'aws-cdk-lib/aws-s3';
new s3.CfnBucket(this, 'MyBucket')
.with(new s3.mixins.BucketVersioning())
.with(new s3.mixins.BucketBlockPublicAccess());
Mixins.of(stack).apply(...) applies a mixin to every supported construct in a scope, and requireAll() throws if any construct in the selection can't take it. For teams building internal construct libraries with governance requirements, that's a real cut in boilerplate; my post on CDK best practices covers fitting this into a production codebase.
The CDKTF Deprecation: What It Means for Your Decision
CDK for Terraform (CDKTF) was a HashiCorp project, separate from AWS CDK, that let you define Terraform configuration in TypeScript, Python, Java, C#, or Go using a CDK-style construct model, then deploy it with Terraform. HashiCorp sunset CDKTF and archived its GitHub repository on December 10, 2025. The last release was v0.21.0 in June 2025, and there will be no further updates or compatibility fixes.
HashiCorp's stated reason is that CDKTF "did not find product-market fit at scale," and it is putting that investment into Terraform core. That leaves no HashiCorp-supported way to write Terraform in a general-purpose language. The real choice is AWS CDK, Terraform in HCL, or a third-party option such as Pulumi.
If older material mentions "Terraform CDK" or "AWS CDK for Terraform," it means CDKTF, not AWS CDK.
What to Do If You're Currently on CDKTF
Existing CDKTF projects keep running, but they're unmaintained: every Terraform or provider upgrade from now on is a compatibility risk nobody upstream will fix. Plan the move before something breaks. HashiCorp's guidance offers two paths:
- Standard Terraform HCL. Run
cdktf synth --hclto generate readable HCL as a starting point, then review and clean it up. You stay on the same engine and providers and drop an abstraction layer. - AWS CDK, if your team already uses it. HashiCorp notes this may be more consistent for teams in the AWS CDK ecosystem. Your language skills transfer; the work is replacing provider constructs with CDK equivalents and moving resources under CloudFormation (see Migration Strategies).
Pulumi is a third option only if you need code-first multi-cloud. CDKTF's MPL-2.0 license also allows community forks, but vet a fork's maintenance before betting production on it.
The Licensing Question: Terraform's BSL and What It Means
Terraform's license changed in 2023 and its owner changed in 2025. Neither affects most teams managing their own infrastructure, but both belong in a multi-year tooling decision.
Terraform's License Change Explained
HashiCorp announced on August 10, 2023 that future releases would move from the Mozilla Public License 2.0 to the Business Source License (BSL) 1.1. For Terraform, that starts with version 1.6.0; 1.5.x and earlier stay under MPL 2.0.
The BSL allows production use, including managing your own infrastructure, but restricts hosted or embedded offerings that compete with HashiCorp. Each BSL release converts to MPL 2.0 four years after it's published. IBM completed its acquisition of HashiCorp on February 27, 2025, and AWS Prescriptive Guidance now lists the license change as a Terraform disadvantage.
Practical Implications for Your Organization
For most users: no change. You can still use Terraform to manage your infrastructure.
For vendors: review the license with legal counsel if your product hosts or embeds Terraform.
For open-source policies: the BSL is source-available, not open source, which matters if your policy requires OSI-approved licenses.
For long-term planning: AWS funds CDK through the AWS usage it drives. HashiCorp, now under IBM, earns from Terraform through HCP Terraform and Terraform Enterprise, so license terms are a business lever that can move again.
OpenTofu as an Alternative
OpenTofu is the community fork created after the license change. It's MPL 2.0 licensed, stewarded by the Linux Foundation, and aims to stay compatible with Terraform configuration and providers. Consider it if open-source licensing is a hard requirement; the trade-off is a smaller commercial ecosystem and features that will diverge from Terraform's over time.
Provisioning Speed: CDK vs Terraform vs Pulumi
CDK can be slower than Terraform for the same change because CloudFormation sits in the deploy path. How much slower depends on your resources. I haven't found an independent head-to-head benchmark, so time your own stack. The mechanism is well documented, though, and AWS changed CloudFormation's defaults in 2026.
Why CDK Deploys Through CloudFormation
CDK does not provision resources itself:
cdk synthcompiles your code into CloudFormation templates locally- The CDK CLI uploads assets to S3 and ECR in the bootstrapped environment
- The CLI submits the template to CloudFormation
- CloudFormation provisions your resources
Most of the extra time sits in step 4. CloudFormation waits for each resource to stabilize, meaning it's actually ready and not just accepted by the API, before marking it complete and starting its dependents. It also tracks every resource for automatic rollback. You pay for that safety in wall-clock time.
How Terraform and Pulumi Deploy Directly
Terraform and Pulumi skip that layer. terraform plan compares state with your configuration, and terraform apply calls provider APIs directly in dependency order, running up to 10 operations concurrently by default (-parallelism). There's no CloudFormation wait, though the provider still waits for slow resources before dependents can use them.
What AWS Changed in 2026 and What to Expect
AWS narrowed the gap in 2026, and older CDK options help during development:
- Faster defaults (2026): CloudFormation's default mode still runs stabilization checks, but it now moves on as soon as each resource is ready, so dependent resources start earlier and stacks with long dependency chains gain the most. No code changes needed.
- Express mode (June 2026):
cdk deploy --expressskips extended stabilization for deploys AWS says are up to 4x faster, a figure from AWS's internal benchmarks. Rollback is disabled by default, so AWS positions it for development and keeps default mode for production. - Hotswap and
cdk watch:cdk deploy --hotswapupdates Lambda code, Step Functions definitions, and ECS container assets through service APIs instead of a change set, andcdk watchredeploys on every save. The CDK docs say this deliberately introduces drift, so keep it to development.
For production, CloudFormation still trades some speed for stabilization checks and rollback. For the development loop, express mode and hotswap narrow the gap. If speed weighs heavily, deploy one representative stack with both tools in a scratch account and time it.
Core Differences That Matter
These are the differences you'll feel every week, long after the tool decision.
Language and Syntax
With CDK you write in a language you know, with full IDE support: autocomplete, type checking, refactoring. Strong typing catches configuration errors before deploy. With Terraform you learn HCL, a small declarative language with editor support through plugins. HCL is easier for non-developers to read, which matters on ops-heavy teams.
Multi-Cloud vs AWS-Native Focus
Terraform's strength: thousands of providers cover other clouds and SaaS (GitHub, Datadog, Kubernetes). If you manage anything beyond AWS, Terraform likely has a provider.
CDK's focus: deep AWS integration. You cannot deploy Azure or GCP resources with CDK, and SaaS resources only through third-party CloudFormation registry extensions.
AWS feature availability: CDK's L1 constructs are generated from CloudFormation's resource definitions, so new resources arrive as CloudFormation supports them. On the Terraform side, the hashicorp/aws provider releases frequently (version 6 went GA in June 2025 with a per-resource region argument), and the awscc provider, GA since May 2024, is generated from CloudFormation schemas through the Cloud Control API and released weekly. Between the two, Terraform teams can usually reach new AWS resources without a long wait.
Abstraction Levels: Constructs vs Modules
This is where CDK's advantage is most visible. Here's an ECS Fargate service behind an Application Load Balancer in each tool.
CDK (L3 construct, roughly 8 lines of meaningful code):
import * as ecs from 'aws-cdk-lib/aws-ecs';
import { ApplicationLoadBalancedFargateService } from 'aws-cdk-lib/aws-ecs-patterns';
const service = new ApplicationLoadBalancedFargateService(this, 'MyService', {
taskImageOptions: {
image: ecs.ContainerImage.fromRegistry('my-app:latest'),
},
memoryLimitMiB: 512,
cpu: 256,
desiredCount: 2,
publicLoadBalancer: true,
});
Terraform (about 70 lines, before security groups and IAM roles):
resource "aws_ecs_cluster" "main" {
name = "my-cluster"
}
resource "aws_ecs_task_definition" "app" {
family = "my-app"
network_mode = "awsvpc"
requires_compatibilities = ["FARGATE"]
cpu = 256
memory = 512
execution_role_arn = aws_iam_role.ecs_execution.arn
container_definitions = jsonencode([{
name = "app"
image = "my-app:latest"
portMappings = [{
containerPort = 80
protocol = "tcp"
}]
}])
}
resource "aws_lb" "main" {
name = "my-alb"
internal = false
load_balancer_type = "application"
security_groups = [aws_security_group.alb.id]
subnets = var.public_subnet_ids
}
resource "aws_lb_target_group" "app" {
name = "my-app-tg"
port = 80
protocol = "HTTP"
vpc_id = var.vpc_id
target_type = "ip"
}
resource "aws_lb_listener" "http" {
load_balancer_arn = aws_lb.main.arn
port = 80
protocol = "HTTP"
default_action {
type = "forward"
target_group_arn = aws_lb_target_group.app.arn
}
}
resource "aws_ecs_service" "app" {
name = "my-app"
cluster = aws_ecs_cluster.main.id
task_definition = aws_ecs_task_definition.app.arn
desired_count = 2
launch_type = "FARGATE"
network_configuration {
subnets = var.private_subnet_ids
security_groups = [aws_security_group.ecs_tasks.id]
assign_public_ip = false
}
load_balancer {
target_group_arn = aws_lb_target_group.app.arn
container_name = "app"
container_port = 80
}
}
# Plus: security groups, IAM roles, ECS task execution role...
With no cluster passed in, the CDK construct creates a VPC, the cluster, task definition, service, ALB, target group, listener, security groups, and IAM roles with production-ready defaults. Terraform gives you explicit control over each resource, and you maintain that explicitness. Community modules can shrink the Terraform side, but then you're trusting someone else's defaults, the same trade CDK asks you to make.
Terraform's advantage is that you see exactly what's created: no hidden resources, no magic defaults. CDK's is less boilerplate with AWS best practices built in. For deep dives, see my posts on CDK constructs and CDK stacks.
Learning Curve Reality Check
For developers: CDK is easier. Familiar languages, existing tooling, and no new syntax.
For ops teams: Terraform is easier. Describing an end state is simpler than learning to program.
For mixed teams: HCL is the neutral middle ground both groups can read.
Each tool hides its own complexity. With CDK, you still need to understand CloudFormation, because a failed deploy means reading CloudFormation events. With Terraform, state management takes time to master, and you'll learn the state file's quirks the hard way.
State Management Philosophy
State is where the two tools diverge most. CDK hands it to an AWS service; Terraform hands it to you.
CDK's CloudFormation-Managed State
CloudFormation tracks each stack's resources inside the service, with no state file to store, lock, or secure. cdk drift runs CloudFormation drift detection against the live resources, while cdk diff compares your local code with the deployed template. Use cdk diff before a deploy and cdk drift as a health check after.
Advantages:
- Zero state management overhead
- Built-in locking, so no concurrent deployment conflicts on a stack
- No state storage to secure and no state file that could leak values
- State visible in the CloudFormation console and API
Limitations:
- Bound by CloudFormation quotas, such as 500 resources per template; nested stacks raise that to 2,500 resources per operation
- You can't inspect or edit state directly the way
terraform stateallows
Terraform's Manual State Configuration
Terraform stores state as JSON (terraform.tfstate), locally by default. Teams configure a remote backend, which for AWS users is almost always S3:
terraform {
backend "s3" {
bucket = "myorg-terraform-states"
key = "myapp/production/tfstate"
region = "us-east-1"
use_lockfile = true
}
}
use_lockfile = true turns on S3 native state locking, added in Terraform 1.10 and generally available since 1.11. It defaults to false, so set it explicitly. The S3 backend docs state that DynamoDB-based locking "is deprecated and will be removed in a future minor version," and AWS's Terraform backend best practices recommend native locking with required_version = ">= 1.11".
Advantages:
- Full control over state storage, versioning, and backup
- Works the same way across providers
- You can inspect and manipulate state when needed
Challenges:
- Encryption, access controls, and locking are yours to configure
- State can hold sensitive values (passwords, connection strings) in plain text
- Team coordination around state requires discipline
The consequence: encrypt the state bucket with SSE-KMS, restrict IAM access to it, and enable versioning so you can recover from a bad state write. CDK's managed state avoids that whole category of work.
Setup and Prerequisites
Both tools need some infrastructure before your first real deploy. CDK creates it with one command; Terraform leaves it to you.
CDK Bootstrap Requirements
CDK needs a bootstrap per AWS account and Region. cdk bootstrap deploys the CDKToolkit CloudFormation stack, which creates:
- S3 bucket for file assets such as Lambda code (
cdk-hnb659fds-assets-ACCOUNT-REGION) - ECR repository for Docker image assets
- IAM roles:
CloudFormationExecutionRole,DeploymentActionRole,FilePublishingRole,ImagePublishingRole,LookupRole
The CDK docs list Node.js 22.x or later as a prerequisite for every CDK language. Bootstrapping is safe to repeat, and AWS recommends rerunning it when a new bootstrap template version ships. My guide on AWS CDK bootstrapping covers the details.
For a working baseline, the AWS CDK Starter Kit gives you GitHub Actions deployments with OIDC instead of long-lived credentials, branch-based preview environments, and a Projen-managed project structure.
See the documentation for setup instructions.
Terraform Backend Setup
Terraform has no bootstrap command. You create a versioned S3 bucket with SSE-KMS encryption and IAM policies restricting access, then point the backend at it with use_lockfile = true. Those resources must exist before Terraform can use them, a chicken-and-egg problem teams usually solve with a small bootstrap script or a separate Terraform root.
The AWS Terraform Starter Kit handles that bootstrap: one command sets up the S3 backend with native state locking and GitHub OIDC, and it ships with GitHub Actions CI/CD plus TFLint and Checkov scanning.
See the documentation for setup instructions.
Deployment Workflow Comparison
Day to day, both tools follow a preview-then-apply loop. They differ in what happens when a deploy fails halfway through.
CDK: Synth to Deploy to Rollback
- Synthesis:
cdk synthconverts your code into CloudFormation templates - Preview:
cdk diffshows changes against the deployed stack - Deploy:
cdk deployuploads assets (Lambda code to S3, Docker images to ECR) and creates or updates the stack - Rollback: in default mode, CloudFormation rolls back automatically on failure
# Preview changes
cdk diff
# Deploy a specific stack
cdk deploy MyStack
# Deploy all stacks
cdk deploy "*"
Automatic rollback returns a failed production deploy to its last working state. For development stacks, cdk deploy --express trades that rollback for speed.
Terraform: Init to Plan to Apply
- Initialize:
terraform initdownloads providers and configures the backend - Plan:
terraform planshows changes against state - Apply:
terraform applyprovisions or updates infrastructure and writes state - Destroy:
terraform destroyremoves everything it manages
# Initialize (first time or when providers change)
terraform init
# Preview changes
terraform plan
# Apply changes
terraform apply
# Tear down everything
terraform destroy
No automatic rollback: if an apply fails partway, the resources already created stay in place and in state. You fix the configuration and apply again.
Previewing Changes: cdk diff vs terraform plan
cdk diff compares your synthesized template with the deployed stack, down to property-level changes. terraform plan refreshes state against real infrastructure by default, then shows attribute-level changes. So cdk diff won't show console changes (that's what cdk drift is for), while terraform plan catches them in the normal preview. Make either preview a mandatory CI/CD gate before production.
Testing Your Infrastructure Code
Both tools now ship a native test framework. The difference is where the tests live and what they run against.
CDK's Built-in Testing Framework
The aws-cdk-lib/assertions module tests the synthesized template, with no AWS account or deployment needed. Fine-grained assertions check specific resource properties and rarely break on CDK upgrades:
import { Template } from 'aws-cdk-lib/assertions';
const template = Template.fromStack(stack);
// Verify Lambda function configuration
template.hasResourceProperties('AWS::Lambda::Function', {
Runtime: 'nodejs22.x',
Handler: 'index.handler',
MemorySize: 256
});
Snapshot tests compare the whole template against a baseline; they catch unintended changes during refactoring but can break on CDK upgrades. Both run in Jest, pytest, JUnit, or NUnit/xUnit.
Terraform's Testing Options
terraform test has been generally available since Terraform 1.6. Tests live in .tftest.hcl files made of run blocks; by default each run applies real infrastructure, and command = plan gives unit-style checks without creating anything. Since 1.7, mock_provider lets you test without real provider calls. Most teams add Terratest (Go) for end-to-end checks and TFLint for provider-specific linting.
Which Approach Fits Your CI/CD Pipeline?
CDK's advantage is that infrastructure tests run in the same language and runner as your application, so npm test or pytest fails the build like it would for app code. Terraform's tests are HCL, which suits teams that live in HCL, and apply-mode tests check real behavior at the cost of time and money. Many teams run plan-mode or mocked tests on every PR and apply-mode tests on a schedule.
Security and Compliance Comparison
Your security team will ask how you catch misconfigurations before deploy and what happens to secrets. The tools answer differently.
Security Scanning Tools
CDK: cdk-nag checks constructs against rule packs (AWS Solutions, HIPAA, PCI DSS, and others), CloudFormation Guard validates synthesized templates, and CDK Aspects run custom checks during synthesis.
Terraform: Checkov and Trivy scan configuration (Checkov also covers CloudFormation, so it works on CDK output), Sentinel provides policy-as-code in HCP Terraform and Terraform Enterprise, and OPA can evaluate Terraform plans.
Terraform has more scanners and policy engines to choose from, largely because more vendors target it.
Policy-as-Code Capabilities
CDK Aspects validate or modify constructs during synthesis; a typical use fails the build if any bucket lacks encryption. Mixins complement them: a mixin adds a feature to constructs you choose, and Mixins.of(scope).requireAll() doubles as a lightweight policy check.
Sentinel and OPA evaluate Terraform plans and can block non-compliant changes. If you need policy enforcement with approval workflows across many teams, Terraform's ecosystem is more established.
Secret Management Approaches
For both tools, keep secrets in AWS Secrets Manager or Parameter Store, never in code.
// CDK: reference an existing secret
const secret = secretsmanager.Secret.fromSecretNameV2(
this, 'MySecret', 'my-secret-name'
);
# Terraform: read the secret through a data source
data "aws_secretsmanager_secret_version" "my_secret" {
secret_id = "my-secret-name"
}
CDK's secret references resolve at deploy time through CloudFormation, so the value stays out of your synthesized template. Values read through Terraform data sources land in the state file, which makes state protection a security control, not housekeeping. Since Terraform 1.10, an ephemeral "aws_secretsmanager_secret_version" block reads the secret without writing it to plan or state, and write-only arguments (1.11+) pass it to resources that support them.
Drift Detection and Remediation
cdk drift runs CloudFormation drift detection, which checks only properties you set explicitly, doesn't support every resource type, and doesn't check nested stacks from the parent (details). Remediation means redeploying or fixing the resource.
Terraform detects drift in every terraform plan, shows it without proposing config changes via terraform plan -refresh-only, and fixes it with terraform apply. Terraform wins here, because drift detection lives inside the normal workflow.
Honest Pros and Cons
Both tools are mature enough for production AWS work, so the trade-offs below are about fit, not capability.
AWS CDK Advantages and Limitations
Advantages:
- Programming languages with full IDE support and compile-time type checking
- High-level abstractions: L2/L3 constructs cut boilerplate and encode AWS defaults
- Managed state and locking with zero configuration
- Automatic rollback on failed deploys
- Tests in your app's toolchain: Jest, pytest, JUnit, or xUnit
- Reusable constructs shared through npm, PyPI, Maven, and NuGet
- Active feature set: Toolkit Library, Mixins, and Refactor (preview)
Limitations:
- AWS-only: no other clouds, and SaaS only through third-party CloudFormation extensions
- CloudFormation underneath: you inherit its quotas, behaviors, and error messages
- Bootstrapping per account and Region
- Deploy wait: stabilization makes some default-mode deploys slower than direct API calls
- Programming required: steeper for traditional ops teams
- Construct gaps: not every service has L2/L3 constructs, so you fall back to L1
Terraform Advantages and Limitations
Advantages:
- Multi-cloud and SaaS: thousands of providers, one workflow
- Large ecosystem: public modules, tooling, and community answers
- Declarative HCL: readable for mixed-skill teams
- Drift detection in every plan
- Direct API calls: no CloudFormation stack in the path
- Native testing:
terraform test, with mocking since 1.7
Limitations:
- Manual state management: backend, encryption, IAM, and locking are yours
- Sensitive state: secrets read through data sources sit in state in plain text unless you use ephemeral resources
- No automatic rollback for failed applies
- License: BSL for 1.6.0 and later, not open source
- State locking migration: DynamoDB locking users need to move to
use_lockfile - New language for application developers
Real-World Experiences
Feature lists say what a tool can do. These are the problems teams typically run into once they use one.
Common Gotchas and Pain Points
CDK gotchas:
- Stacks can fail mid-update: one stuck in
UPDATE_ROLLBACK_FAILEDneeds manual intervention - Constructs synthesize to surprising CloudFormation: check
cdk synthoutput when behavior doesn't match - Cross-stack references create export locks: the producing stack can't remove an output while another stack imports it (fixes here)
- Outdated bootstrap stacks cause confusing errors after upgrades
Terraform gotchas:
- State corruption from concurrent runs without locking
- Sensitive data in state: protect the bucket like a secrets store
- Provider upgrades can break existing code, so pin versions
- Plan doesn't catch every error: some appear only during apply, after partial changes
When the Pros Become Cons
- CDK's "programming flexibility" turns into "too much magic" when you're debugging synthesized CloudFormation
- CDK's "high-level abstractions" turn into "I can't customize this" when an L2/L3 construct doesn't fit
- Terraform's "declarative simplicity" turns into "I can't express this logic" for complex conditional resources
- Terraform's "manual state control" turns into a state file nightmare as the team grows
Decision Framework
Who owns the infrastructure code predicts the right tool better than any feature list.
The Role-Based Decision
The organizing question: who writes and maintains the infrastructure code every day? It matters more than any feature comparison.
Software developers and application engineers: CDK is the natural fit. You work in the language you know, keep infrastructure tests in your existing suite, and move fast on AWS with L2/L3 constructs.
DevOps/SRE and platform engineers: Terraform typically wins. Declarative configuration reads well for infrastructure roles, state gives operational control, and the ecosystem maps to platform workflows.
Mixed teams or no clear IaC owner: HCL is the neutral middle ground. CDK needs someone who can program, and that person has to be available when things break.
Training 10 ops engineers to program is a different investment from teaching 10 developers HCL, so ask the role question before opening any feature matrix.
Choose CDK If
- Your infrastructure is 100% AWS with no multi-cloud requirement in sight
- Your team are developers who prefer TypeScript, Python, Java, C#, or Go over HCL
- You want L2/L3 constructs to cut boilerplate and encode AWS defaults
- You want infrastructure tests in the same language and runner as your application
- You're building AWS-native serverless or container applications
- You want to distribute internal constructs that enforce your standards
Choose Terraform If
- You need multi-cloud or hybrid cloud
- You manage non-AWS resources (GitHub, Datadog, Kubernetes) alongside AWS
- Avoiding vendor lock-in is a strategic principle
- Your team is ops-focused and prefers declarative configuration
- You already have Terraform expertise and modules
- You want drift detection in every plan and deploys that call AWS APIs directly
Use Case Decision Matrix
| Use Case | CDK | Terraform | Why |
|---|---|---|---|
| Serverless applications | Best | Good | L3 constructs for Lambda and API Gateway reduce boilerplate |
| Container orchestration (ECS/EKS) | Best | Good | Patterns like ApplicationLoadBalancedFargateService simplify setups |
| Multi-account AWS Organizations | Good | Good | CDK if developers manage it, Terraform if a central ops team does |
| Network infrastructure (VPC, Transit Gateway) | Good | Best | Mature modules and declarative config fit network setups |
| Multi-cloud deployments | No | Best | CDK doesn't support other clouds |
| Kubernetes infrastructure | EKS only | Best | Terraform's Kubernetes provider fits any cluster; CDK deploys manifests and Helm charts to EKS |
| Third-party SaaS (GitHub, Datadog) | Limited | Best | CDK reaches SaaS only via third-party CloudFormation extensions |
| AWS-only with compliance requirements | Best | Good | Aspects, Mixins, and cdk-nag enforce policy at synthesis |
For multi-account architectures, see my guide on AWS multi-account best practices. If the decision is really about how you vend and baseline accounts, the same CDK-or-Terraform split shows up in Account Factory for Terraform vs a CDK landing zone, and Control Tower alternatives covers the wider set of options.
Hybrid CDK + Terraform: When to Use Both
This section is for teams that already know they need both tools. If you're still deciding, pick one; hybrid setups rarely pay off without a concrete reason. The real question is where to draw the boundary.
The Layered Architecture Pattern
A pattern that holds up well is vertical separation by resource lifespan and ownership.
Terraform manages the foundation layer: resources that change rarely, serve multiple teams, and must exist before any CDK stack deploys:
- VPC and networking (subnets, route tables, NAT gateways)
- Shared IAM roles and permission boundaries
- Transit Gateway for multi-VPC routing
- Route 53 hosted zones and shared security groups
CDK manages the application layer: resources owned by one service and deployed often by its team:
- Lambda functions and API Gateway
- ECS services and task definitions
- Application-specific S3 buckets, queues, and DynamoDB tables
The boundary rule: if a resource is shared across multiple CDK stacks or teams, it belongs in Terraform. If one application owns it, it belongs in CDK.
Excalidraw diagram loading.
Sharing State Between CDK and Terraform
SSM Parameter Store is the usual bridge. Terraform exports outputs to SSM:
resource "aws_ssm_parameter" "vpc_id" {
name = "/platform/vpc/id"
type = "String"
value = aws_vpc.main.id
}
resource "aws_ssm_parameter" "private_subnet_ids" {
name = "/platform/vpc/private-subnet-ids"
type = "StringList"
value = join(",", aws_subnet.private[*].id)
}
CDK reads them at synthesis time:
import * as ssm from 'aws-cdk-lib/aws-ssm';
const vpcId = ssm.StringParameter.valueFromLookup(this, '/platform/vpc/id');
// StringList parameters come back as one comma-separated string
const privateSubnetIds = ssm.StringParameter.valueFromLookup(this, '/platform/vpc/private-subnet-ids').split(',');
Lookups need a stack with an explicit account and Region, and CDK caches the values in cdk.context.json. If the Terraform foundation hasn't run yet, cdk synth fails. That's intentional: it enforces deployment order and makes the dependency explicit.
When Hybrid Adds More Complexity Than Value
Solo developers and small startups: don't do this. Two toolchains, two CI/CD patterns, and two state models aren't worth it at that size.
Hybrid makes sense for:
- Large organizations with a platform team (Terraform) and application teams (CDK)
- A gradual migration from one tool to the other
- An existing Terraform foundation not worth rewriting, with CDK for new applications
- A multi-cloud foundation (Terraform) under an AWS-native application layer (CDK)
The cost is real: two toolchains in CI/CD, two PR review patterns, and overlapping resource ownership if teams don't hold the boundary. When the boundary needs to move, you need a migration plan.
Migration Strategies
Requirements change, and sometimes the first choice was wrong. Both directions are possible, and neither is automatic.
Migrating from Terraform to CDK
AWS's tool is cdk migrate, which the CLI reference still labels experimental. It generates L1 constructs only, so getting to L2/L3 is manual work afterwards.
# Migrate from a deployed CloudFormation stack
cdk migrate --from-stack --stack-name "myCloudFormationStack"
# Migrate from a local CloudFormation template
cdk migrate --from-path "./template.json" --stack-name "myCloudFormationStack"
# Migrate from deployed resources (uses IaC generator scan)
cdk migrate --from-scan --stack-name "myStack"
It handles one stack per migration, doesn't support nested templates or migrate Lambda code and assets, and reads CloudFormation stacks, templates, or deployed resources, never Terraform state. For Terraform-managed resources:
- Define the resources in a CDK app and bring them under CloudFormation with
cdk import(or generate a whole app withcdk migrate --from-scan) - Run
cdk diffto confirm the stack shows no pending changes - Hand the resources over from Terraform: delete their resource blocks and run
terraform state rm, or replace the blocks with aremovedblock set todestroy = false(Terraform 1.7+). Removing state alone makes the nextterraform applyrecreate them - Refactor L1 constructs to L2/L3 where it's worth it
For stateful resources such as databases and buckets, confirm the type supports CloudFormation import and set a retain policy before you start. Coming from CDKTF? See What to Do If You're Currently on CDKTF.
Migrating from CDK to Terraform
There's no CDK-aware tool for this direction:
- Write
importblocks for the existing resources;terraform plan -generate-config-out=generated.tfdrafts matching HCL (experimental since 1.5) for you to review - Bring them into state with
terraform apply - Run
terraform planand confirm no changes, testing in non-production first - Remove the resources from the CDK stacks with a retain policy, so deleting the stack doesn't delete them
The work is resource by resource, and CloudFormation-specific configuration doesn't always translate. For large estates, a blue/green rebuild can be simpler. Both directions have only partial, experimental tooling, so budget for manual work either way.
Risk Mitigation for Lock-In Concerns
Both tools create lock-in. CDK's is twofold, the tool plus AWS through CloudFormation; Terraform's is tool lock-in with platform flexibility through providers. To keep a future switch affordable, keep infrastructure modular, document architectural decisions with tool-independent diagrams, invest in tests that let you refactor with confidence, and plan gradual migrations over big-bang rewrites. If lock-in is your main worry, Terraform gives you more room by design.
Conclusion: Making Your Decision with Confidence
The comparison comes down to scope and people.
Key Takeaways
- AWS CDK wins for AWS-native developer teams: programming languages, managed state with automatic rollback, L2/L3 abstractions, and an active feature set
- Terraform wins for multi-cloud and platform teams: declarative HCL, thousands of providers, direct API calls, and native testing, at the cost of state you manage and a BSL license
- CDKTF is over: move to Terraform HCL with
cdktf synth --hcl, or to AWS CDK if your team already uses it - Speed matters less than it used to: CloudFormation's stabilization waits can slow CDK, but AWS's 2026 defaults, express mode, and hotswap narrow the gap. Time your own stack instead of trusting a multiplier
- Hybrid works with clear boundaries: Terraform for the foundation, CDK for applications, SSM Parameter Store as the bridge
Your Next Action Step
Build the same small stack (VPC, Lambda, S3) in both tools in a scratch AWS account, time the deploys, and notice which workflow your team finds natural. Then commit within two weeks; indecision costs more than picking either.
If you're choosing CDK:
- Install AWS CDK:
npm install -g aws-cdk - Deploy your first CDK app in 60 minutes
- Review CDK best practices for production-ready patterns
- Learn about bootstrapping: AWS CDK Bootstrap: The Why and the How
- Plan your layout: Optimize your AWS CDK Project Structure for Growth
If you're choosing Terraform:
- Install Terraform with HashiCorp's installation guide
- Read AWS Prescriptive Guidance for Terraform
- Set up an S3 backend with
use_lockfile = true, not DynamoDB locking - Review Terraform AWS Provider Best Practices
What's your biggest hesitation in making this choice? Drop a comment below and let's discuss.
Next step