Skip to main content

Terraform vs AWS CDK: Infrastructure as Code Decision Guide

DevOps & CI/CDUpdated Manoj V.8 min read

Quick summary: CDK v2 and TypeScript when the estate is AWS-only and the team writes tests. Terraform when the same config must own Datadog, GitHub, or PagerDuty. CDK v1 ended support on June 1, 2023. A CloudFormation stack stops at 500 resources.

Key Takeaways

  • CDK v2 and TypeScript when the estate is AWS-only and the team writes tests
  • CDK v1 ended support on June 1, 2023
  • A CloudFormation stack stops at 500 resources
  • As of May 2026, new CDK work targets v2 only: CDK v1 ended support on June 1, 2023
  • It entered maintenance on June 1, 2022
Dashboard titled Terraform vs CDK, with an HCL file on the left and TypeScript constructs on the right, both pointing at one cloud icon
Table of Contents

Most teams who say they might go multi-cloud never do. AWS-only teams still run GitHub, Datadog, and PagerDuty. That is the trade-off. The rest of this page is how state, tests, and day-two work differ once you have picked.

How the two tools differ

Terraform is a declarative, multi-cloud IaC tool. You describe the desired state of your infrastructure in HCL (HashiCorp Configuration Language), and Terraform figures out what changes to make. It works with AWS, Azure, GCP, and hundreds of other providers.

AWS CDK is an imperative, AWS-native IaC tool. You write infrastructure definitions in a general-purpose programming language (TypeScript, Python, Java, C#, Go), and CDK synthesizes CloudFormation templates. It generates the same declarative CloudFormation that AWS uses internally.

The practical implication: Terraform users think in terms of resources and their properties. CDK users think in terms of constructs and programming patterns: loops, conditionals, inheritance, and composition.

Language and developer experience

Terraform (HCL)

HCL is a domain-specific language designed specifically for infrastructure configuration:

resource "aws_lambda_function" "processor" {
  function_name = "order-processor"
  # ⚠️ nodejs20.x reaches EOL on April 30, 2026 — migrate to nodejs22.x
  runtime       = "nodejs22.x"
  handler       = "index.handler"
  role          = aws_iam_role.lambda_role.arn
  timeout       = 30
  memory_size   = 256

  environment {
    variables = {
      TABLE_NAME = aws_dynamodb_table.orders.name
    }
  }
}

Node.js runtime EOL notice (April 30, 2026): The nodejs20.x Lambda runtime (updated to nodejs22.x in examples above) reached end-of-life on April 30, 2026. Audit your Lambda functions and IaC definitions and migrate any remaining nodejs20.x functions to nodejs22.x. Node.js 22 (LTS) is the current supported version.

Advantages:

  • Purpose-built for infrastructure: concise, readable, no boilerplate
  • Easy to learn for operations engineers who are not software developers
  • Consistent syntax regardless of provider
  • Strong IDE support (VS Code extension, syntax highlighting, autocompletion)

Limitations:

  • Limited programming constructs: loops (for_each, count) and conditionals are available but less expressive than general-purpose languages
  • Complex logic (dynamic resource generation based on configuration) can become verbose
  • No native testing framework (requires external tools like Terratest)

AWS CDK (general-purpose languages)

CDK uses familiar programming languages:

const processor = new lambda.Function(this, 'OrderProcessor', {
  functionName: 'order-processor',
  // ⚠️ NODEJS_20_X reaches EOL on April 30, 2026 — migrate to NODEJS_22_X
  runtime: lambda.Runtime.NODEJS_22_X,
  handler: 'index.handler',
  timeout: Duration.seconds(30),
  memorySize: 256,
  environment: {
    TABLE_NAME: ordersTable.tableName,
  },
});

// Grant permissions automatically
ordersTable.grantReadWriteData(processor);

Advantages:

  • Full power of a general-purpose language: loops, conditionals, classes, interfaces, generics
  • Strong typing catches configuration errors at compile time (TypeScript)
  • IDE autocompletion shows every available property and valid value
  • Native testing with familiar frameworks (Jest, pytest, JUnit)
  • L2 and L3 constructs abstract away boilerplate (the grantReadWriteData call above generates a correctly scoped IAM policy automatically)

Limitations:

  • Infrastructure code looks like application code, which can blur the distinction between “what to deploy” and “how to deploy it”
  • More lines of code for simple resources compared to HCL
  • CDK’s abstraction layers can obscure what CloudFormation is actually generated
  • Debugging requires understanding both CDK constructs and CloudFormation behavior

State management

Terraform state

Architecture diagram of Terraform state in S3 with a DynamoDB lock

Figure: Terraform state lives in an S3 file. DynamoDB locks that file so two applies do not write at once. Open the draw.io source.

Terraform maintains a state file that maps your configuration to real-world resources. The state file is how Terraform knows what exists, what changed, and what to destroy.

State backends:

  • S3 + DynamoDB: The standard remote backend for AWS. S3 stores the state file; DynamoDB provides locking to prevent concurrent modifications.
  • Terraform Cloud/Enterprise: Managed state with collaboration features, access controls, and run history.
  • Local file: Default, and the wrong default for a team or for production. Drift after a console change, a corrupted file, and secrets sitting in state are the failures in the list below. Versioned S3 plus a DynamoDB lock is the backend that addresses them.

State challenges:

  • State drift: If someone modifies infrastructure outside Terraform (console, CLI), state becomes inaccurate. terraform refresh or terraform plan detects drift.
  • State file corruption: Rare but catastrophic. Mitigated by S3 versioning and DynamoDB locking.
  • State splitting: Large monolithic state files become slow to plan. Teams split state into smaller, scoped configurations (e.g., per-service or per-environment).
  • Secrets in state: Terraform stores resource attributes in state, including sensitive values like database passwords. State files must be encrypted and access-controlled.

CDK state (CloudFormation)

Architecture diagram of AWS CDK deploying through a CloudFormation stack

Figure: CDK deploys a CloudFormation stack, and that stack is the state. There is no separate lock to configure. Open the draw.io source.

CDK delegates state management entirely to CloudFormation. Each CDK stack becomes a CloudFormation stack, and CloudFormation tracks the state of every resource it manages.

Advantages over Terraform state:

  • No state file to manage, back up, or protect
  • No state locking to configure
  • No drift between state file and reality (CloudFormation is the source of truth)
  • CloudFormation drift detection built in

Disadvantages:

  • CloudFormation stack limits (500 resources per stack) require careful stack splitting
  • CloudFormation updates can be slower than Terraform applies
  • Rollback behavior can be confusing: CloudFormation rolls back the entire stack if any resource fails, which can cause cascading issues

Multi-cloud vs AWS-native

Terraform: multi-cloud

Terraform’s provider model supports any cloud or service with an API. A single Terraform configuration can manage:

# AWS resources
resource "aws_s3_bucket" "data" { ... }

# Datadog monitoring
resource "datadog_monitor" "alert" { ... }

# GitHub repository
resource "github_repository" "app" { ... }

# PagerDuty escalation
resource "pagerduty_escalation_policy" "ops" { ... }

This is Terraform’s strongest advantage for organizations that use multiple clouds or manage non-AWS resources (DNS providers, SaaS tools, monitoring services) alongside their AWS infrastructure.

Reality check: Most teams that say “we might go multi-cloud” never do. If your organization is committed to AWS, Terraform’s multi-cloud capability is insurance you pay for but rarely use. However, even AWS-only teams often manage GitHub, Datadog, PagerDuty, and other SaaS tools, and Terraform’s provider ecosystem covers all of these.

CDK: AWS-native

CDK is designed exclusively for AWS. It generates CloudFormation, which means:

  • Every AWS service is supported on day one (CloudFormation coverage)
  • L2 constructs provide opinionated, best-practice defaults for common patterns
  • Deep integration with AWS services (CDK Pipelines for CI/CD, CDK Aspects for compliance checks)
  • Cannot manage non-AWS resources (no Datadog, GitHub, PagerDuty providers)

CDK for Terraform (CDKTF): HashiCorp offers CDKTF, which lets you write Terraform configurations using CDK-style programming languages. This gives you CDK’s developer experience with Terraform’s multi-provider support. However, CDKTF is less mature than either CDK or Terraform HCL individually.

Modularity and reuse

Terraform modules

Terraform modules are directories of .tf files that accept input variables and produce outputs:

module "api" {
  source = "./modules/api-gateway"

  name        = "orders-api"
  stage_name  = "production"
  lambda_arn  = module.processor.function_arn
}

Module ecosystem:

  • Terraform Registry has thousands of community modules
  • Company-internal modules shared via Git repositories or private registries
  • Module versioning via Git tags or registry versions

CDK constructs

CDK constructs are classes that can be composed, extended, and shared:

export class ApiStack extends Stack {
  constructor(scope: Construct, id: string, props: ApiStackProps) {
    super(scope, id, props);

    const api = new CompanyApi(this, 'Api', {
      name: 'orders-api',
      handler: props.processorFunction,
      authentication: 'cognito',
    });
  }
}

Construct levels:

  • L1 (CFN resources): Direct CloudFormation resource mapping, lowest level
  • L2 (Curated): AWS-maintained constructs with sensible defaults and helper methods
  • L3 (Patterns): Multi-resource patterns (e.g., LambdaRestApi creates API Gateway + Lambda integration + permissions)

Construct ecosystem:

  • Construct Hub (constructs.dev) has community and partner constructs
  • Company-internal constructs shared as npm/PyPI packages with full versioning
  • Inheritance and composition provide strong reuse patterns

Testing

Terraform testing

Terraform’s built-in testing is limited. Most teams use external frameworks:

  • terraform plan: Preview changes before applying (the most common “test”)
  • terraform validate: Syntax and configuration validation
  • Terratest: Go-based integration testing framework that provisions real infrastructure, validates it, and destroys it
  • Checkov/tfsec: Static analysis for security and compliance policy violations

CDK testing

CDK has first-class testing support using familiar unit testing frameworks:

test('Lambda function has correct timeout', () => {
  const app = new App();
  const stack = new OrderStack(app, 'TestStack');
  const template = Template.fromStack(stack);

  template.hasResourceProperties('AWS::Lambda::Function', {
    Timeout: 30,
    MemorySize: 256,
  });
});

Testing levels:

  • Snapshot tests: Compare synthesized CloudFormation to a known-good snapshot
  • Fine-grained assertions: Validate specific resource properties
  • Validation tests: Test that invalid inputs throw errors at synth time

CDK tests use the same language and runner as the application. Terraform’s built-in checks stop at plan and validate; Terratest and Checkov are extra tools.

Day-two operations

Terraform day-two

  • Plan before apply: terraform plan shows exactly what will change. This is Terraform’s signature workflow and provides high confidence before modifications.
  • Targeted applies: terraform apply -target=aws_lambda_function.processor modifies a single resource without touching others.
  • Import: terraform import brings existing resources under Terraform management.
  • State surgery: terraform state mv, terraform state rm for state file manipulation when refactoring.

CDK day-two

  • Diff before deploy: cdk diff shows CloudFormation changeset before deployment.
  • Hotswap: cdk deploy --hotswap updates Lambda code and some resources without full CloudFormation deployment (development only).
  • Import: CDK supports importing existing resources into stacks, though the process requires more manual steps than Terraform.
  • Refactoring: Moving resources between CDK stacks is more complex than Terraform state operations because CloudFormation manages resource lifecycle.

Team considerations

Choose Terraform when

  • Multi-cloud or multi-provider: You manage resources across AWS, Azure, GCP, or SaaS providers
  • Operations-focused team: Your team has more ops/SRE engineers than software developers
  • Organizational standardization: Your company has standardized on Terraform across teams or business units
  • Existing Terraform investment: Migrating away from working Terraform has high cost and low benefit
  • Strong module ecosystem: Community modules cover your infrastructure patterns

Choose CDK when

  • AWS-only: Your infrastructure is entirely on AWS
  • Developer-focused team: Your team is primarily software developers who prefer TypeScript/Python
  • Complex infrastructure logic: You need conditionals, loops, and composition that HCL handles awkwardly
  • Testing culture: Your team values unit testing infrastructure alongside application code
  • CDK construct reuse: You want to package and share infrastructure patterns as typed libraries with autocompletion

Migration between tools

Terraform to CDK

The cdk import command can bring existing CloudFormation stacks under CDK management. For Terraform-managed resources, the process is:

  1. Export resource configurations from Terraform state
  2. Write equivalent CDK constructs
  3. Import existing resources into CDK stacks
  4. Remove resources from Terraform state (without destroying them)

This is a non-trivial migration. For a large infrastructure, plan for weeks.

CDK to Terraform

  1. Use CloudFormation outputs to identify resource ARNs and IDs
  2. Write equivalent Terraform configurations
  3. Import resources into Terraform state using terraform import
  4. Delete CloudFormation stacks with DeletionPolicy: Retain on all resources

Our recommendation

CDK v2 with TypeScript, for an AWS-only estate whose authors already write tests. Terraform, when that same repository must also own Datadog, GitHub, or PagerDuty, or when the team already runs Terraform and a migration would cost more than it returns.

This page does not cover CDK vs CloudFormation vs Blocks or Terraform vs CloudFormation. It also does not cover a migration duration. Moving a large estate either direction is weeks of import work, and this file does not have a timed migration to cite.

For the build itself, see serverless on AWS and DevOps pipeline setup.

Contact us to implement infrastructure as code →

Frequently asked questions

When should an AWS-only TypeScript team not pick Terraform?
When the estate is AWS-only and the people who change it already write tests in TypeScript. CDK v2 synthesizes CloudFormation, catches bad config at compile time, and tests the template with the same runner as the application. Terraform is the extra language in that case.
When should you not pick CDK?
When the same configuration must own SaaS beside AWS. CDK cannot manage Datadog, GitHub, or PagerDuty. Terraform can. CDK for Terraform exists and is less mature than either CDK or Terraform HCL on its own.
What fails if Terraform state stays on a laptop?
Local state is the default, and this page already treats it as wrong for a team. The failures listed here are drift after a console edit, a corrupted state file, and secrets sitting in that file. Put the file in versioned, encrypted S3 and lock it with DynamoDB.
What fails if a CDK stack is not split before 500 resources?
CloudFormation stops a stack at 500 resources. A monolith stack then fails to update. Split by service or environment before you reach the quota, the same way a large Terraform state gets slow to plan and has to be split.
Does "we might go multi-cloud" justify Terraform?
Usually no. Most teams who say they might go multi-cloud never do. The reason to keep Terraform on an AWS estate is the SaaS providers in the same config, not a second cloud you have not bought.
Manoj V.
Manoj V.

Enterprise AI Transformation

Enterprise AI transformation and implementation leader focused on pilot-to-production playbooks, with a background in financial services. Writes the FactualMinds guides on serverless, CI/CD, and DevOps on AWS, the delivery plumbing production AI depends on.

Enterprise AI TransformationPilot to ProductionFinancial ServicesAWS ServerlessCI/CDDevOps

Recommended Reading

Explore All Articles »