AWS CDK vs Terraform: Choosing Your Infrastructure as Code Tool

When your AWS footprint grows beyond a handful of manually created resources, Infrastructure as Code becomes non-negotiable. I have led teams that adopted both AWS Cloud Development Kit (CDK) and Terraform on the same organization at different stages, and the question of which to choose comes up on almost every new project kickoff. Both let you define infrastructure in code, version it in Git, and deploy it repeatedly, but they make fundamentally different trade-offs in how they model AWS, manage state, and fit into developer workflows. For beginners looking to standardize, understanding those trade-offs early prevents costly rewrites when you scale to multiple environments, accounts, or teams. This comparison walks through how each tool actually behaves in practice, not just in documentation, so you can align your choice with your team's skills, your cloud strategy, and your operational requirements.

How AWS CDK and Terraform Approach Infrastructure Differently

In my experience, the biggest conceptual difference is not syntax, it is what the tool considers the source of truth. AWS CDK is an abstraction over AWS CloudFormation. You write code in TypeScript, Python, Java, C# or Go using the CDK library, and during synthesis the CDK produces a CloudFormation template. Deployment is then handed off to CloudFormation, which orchestrates the actual API calls to create and update resources. Terraform, by contrast, speaks directly to the AWS APIs through its AWS provider. You describe the desired state in Hashicorp Configuration Language (HCL), and Terraform itself plans and applies the changes without an intermediary orchestration service.

This distinction has practical consequences. Because CDK generates CloudFormation, you get CloudFormation's strengths for free: automatic rollback on failure, stack-level drift handling, and deep integration with AWS service internals. The trade-off is you are fully coupled to CloudFormation's model and its quirks, including stack limits, eventual consistency edge cases, and the way it handles replacements for immutable properties. Terraform gives you direct control over the resource lifecycle and works consistently across providers. In my teams, that has meant we can manage AWS, Cloudflare, Datadog, and GitHub resources from the same workflow, while CDK remains strictly AWS-focused.

Where CloudFormation Helps and Where It Constrains You

For teams that live entirely inside AWS, the CloudFormation foundation is reassuring. I have seen CDK stacks roll back cleanly after a failed RDS parameter group change that would have left a manual deployment in a half-broken state. StackSets also make multi-region deployments straightforward. However, when I needed to provision resources outside AWS or implement custom provisioning logic that CloudFormation does not support natively, CDK required escape hatches or custom resources written as Lambda functions. Terraform's provider ecosystem, documented extensively in the Terraform Documentation, let us keep that logic in one place.

Provider Model vs Construct Library

Terraform extends through providers, each versioned independently. You pin the AWS provider version and get access to the entire AWS API surface, often on day one of a new service launch. CDK extends through constructs. AWS provides L1 constructs that map one-to-one to CloudFormation resources, L2 constructs that add sensible defaults and helper methods, and L3 patterns that assemble multiple services. For example, an aws_s3.Bucket L2 construct automatically creates encryption, versioning options, and permission helpers. In HCL you configure those explicitly. This makes CDK faster for standard patterns but hides complexity that you sometimes need to understand when debugging.

Imperative Logic vs Declarative Configuration: What Changes for Your Team

CDK lets you use a real programming language, which means loops, conditionals, classes, and unit tests work as you expect. Terraform's HCL is declarative with added expression functions and more recently added loops and conditionals, but it is still not a general-purpose language. For developers who already write TypeScript or Python daily, CDK feels natural. I have onboarded backend engineers to CDK in two days because they could apply existing software engineering practices: extract a function to share VPC configuration, write a Jest test to assert a bucket has encryption enabled, and refactor with their IDE.

Terraform's strength lies in its readability and explicitness for infrastructure specialists. A Terraform file describing a VPC, subnets, and a security group can be reviewed by a network engineer who has never written TypeScript. The learning curve for HCL itself is low, though mastering state, modules, and workspaces takes longer. In mixed teams where platform engineers manage infrastructure for developers, I have found Terraform easier to use as a contract language, while CDK is more powerful when application developers own their infrastructure directly alongside their service code.

// CDK (TypeScript) - L2 construct with logic and reuse
import * as cdk from 'aws-cdk-lib';
import * as s3 from 'aws-cdk-lib/aws-s3';
import * as lambda from 'aws-cdk-lib/aws-lambda';

export class AppStack extends cdk.Stack {
  constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    const bucket = new s3.Bucket(this, 'Uploads', {
      versioned: true,
      encryption: s3.BucketEncryption.S3_MANAGED,
      blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
    });

    // Imperative logic: create one function per environment
    for (const env of ['dev', 'staging']) {
      new lambda.Function(this, `Processor-${env}`, {
        runtime: lambda.Runtime.NODEJS_18_X,
        handler: 'index.handler',
        code: lambda.Code.fromAsset('lambda'),
        environment: { BUCKET_NAME: bucket.bucketName, ENV: env },
      });
    }
  }
}
# Terraform (HCL) - declarative resources with for_each and variables
variable "environments" {
  type    = set(string)
  default = ["dev", "staging"]
}

resource "aws_s3_bucket" "uploads" {
  bucket = "company-uploads-${var.account_id}"
}

resource "aws_s3_bucket_versioning" "uploads" {
  bucket = aws_s3_bucket.uploads.id
  versioning_configuration { status = "Enabled" }
}

resource "aws_lambda_function" "processor" {
  for_each      = var.environments
  function_name = "processor-${each.key}"
  runtime       = "nodejs18.x"
  handler       = "index.handler"
  filename      = "lambda.zip"
  environment {
    variables = {
      BUCKET_NAME = aws_s3_bucket.uploads.bucket
      ENV         = each.key
    }
  }
}

Testing and Code Review Implications

With CDK, you can use aws-cdk-lib/assertions to run snapshot tests against the synthesized template in your CI pipeline. I typically add a test that fails if a database is not encrypted or if an S3 bucket allows public access. Terraform offers terraform plan output review, terraform validate, and policy tools like Open Policy Agent or HashiCorp Sentinel. Both approaches work, but CDK tests run with standard test runners like Jest or pytest, which integratse easily into application repos, while Terraform policy checks fit naturally into platform-centric guardrails.

State Management Realities: CDK CloudFormation Stacks Against Terraform State Files

State handling is where beginners underestimate operational risk. CDK itself is stateless; it relies entirely on CloudFormation stacks to track what has been deployed. CloudFormation stores state internally in AWS. You do not manage a state file, you do not lock it, and you do not worry about corruption. If a stack update fails, CloudFormation attempts to roll back to the last known good state automatically. I have found this reduces operational toil for teams that lack remote backend expertise.

Terraform maintains its own state file that maps your configuration to real-world resources. That file must be stored remotely for any team use case, typically in an S3 bucket with DynamoDB for locking, or in Terraform Cloud / HCP Terraform. You are responsible for securing it, versioning it, and ensuring concurrent runs do not conflict. I have recovered Terraform state from S3 versioning after an accidental local apply, and I have also seen teams lose hours because someone ran an apply without remote locking enabled. When following a landing zone approach described in Multi-Account AWS Strategy: Landing Zones, Control Tower and Organization Units, you will need one state backend per account and environment, or a centralized backend with workspaces per account. Both patterns work, but they require explicit design decisions early.

Handling Secrets and Sensitive Data in State

Terraform state stores resource attributes in plaintext by default. If you create an RDS password or a Secrets Manager secret with Terraform, that value can appear in state unless you mark it sensitive and restrict access. CDK does not store resource properties in a local state file, but CloudFormation stack parameters and outputs are visible in the AWS console. In either case, I recommend generating secrets outside your IaC and referencing them, for example by using AWS Secrets Manager with automatic rotation and passing only the ARN through CDK or Terraform.

# Terraform backend configuration - must be bootstrapped before first apply
terraform {
  backend "s3" {
    bucket         = "company-terraform-state"
    key            = "network/prod/terraform.tfstate"
    region         = "us-east-1"
    dynamodb_table = "terraform-locks"
    encrypt        = true
  }
}

If you adopt the principles from AWS Well-Architected Framework: Applying the Five Pillars in Practice, your state backend should meet the same reliability and security pillar requirements as any workload: encrypted at rest, access logged with CloudTrail, and protected by least-privilege IAM policies.

Language Ecosystem and Reusability: CDK Constructs vs Terraform Modules

Reusability looks different in practice. In CDK, you build reusable components as classes that extend Construct. I have built an internal VpcWithPrivateSubnets construct that encapsulates a three-AZ VPC with isolated subnets, VPC endpoints for S3 and DynamoDB, and flow logs shipped to CloudWatch. Application teams import it from a private npm or PyPI package and instantiate it with two lines of code. Because it is code, they can extend it with methods like addDatabaseSubnet() that encapsulate organization-specific networking rules covered in Cloud Networking: VPC Peering, Transit Gateway and PrivateLink.

Terraform modules serve the same purpose but with a different distribution model. You publish a module as a versioned directory with variables, outputs, and resources, often in a private registry or Git repository. The Terraform Registry provides thousands of community modules, but my guidance for beginners is to treat external modules with caution. Pin versions strictly and review the code, especially for security group or IAM resources. In one audit I found a community VPC module that opened 0.0.0.0/0 on port 22 by default for convenience. Internal modules give you control but require discipline to version and document inputs correctly.

Abstraction Level and Escape Hatches

CDK L2 and L3 constructs hide a lot of sensible defaults, which accelerates development for standard architectures like the ones in Serverless Architecture Patterns: API Gateway, Lambda and Step Functions. When you need to set a property that the L2 construct does not expose, you drop to the escape hatch with node.defaultChild to override the underlying L1 resource. Terraform has no hidden defaults; everything you configure is visible in the file. That verbosity means more lines for a basic API Gateway + Lambda stack, but auditing is straightforward because there is no generated template between your code and the plan output.

Drift Detection, Rollbacks, and Day-Two Operations Compared

Day-two operations often decide long-term satisfaction more than initial provisioning speed. CDK inherits CloudFormation's drift detection. You can run drift detection from the console or CLI and see which resources have been modified outside of the stack. Rollbacks are automated and atomic at the stack level; either the whole update succeeds or CloudFormation reverts. This atomicity has saved me during a failed ECS service update where the new task definition was invalid. Terraform detects drift on every plan by refreshing state against the real APIs. It will show you the diff and let you decide whether to re-apply, import, or ignore changes with lifecycle { ignore_changes }.

The operational trade-off is granularity. CloudFormation rolls back the entire stack even if only one resource failed, which can be slow for large stacks and can block unrelated changes while a rollback is in progress. Terraform applies changes resource by resource and stops on error, leaving you to fix forward. I prefer Terraform's approach for platform networking stacks where I want fine-grained control, and CDK/CloudFormation's atomic model for application stacks where consistency matters more than speed.

Capability AWS CDK (via CloudFormation) Terraform (AWS Provider)
State Storage Managed by CloudFormation in AWS, no file to maintain State file in S3, Terraform Cloud, or other backend you configure and secure
Multi-Cloud Support AWS only AWS, Azure, GCP, plus SaaS providers from single configuration
Language & Abstraction TypeScript/Python/Java with L1/L2/L3 constructs and imperative logic HCL declarative with modules, functions, and explicit resource blocks
Rollback Behavior Automatic stack rollback on failure, atomic deployment No automatic rollback, partial applies fail in place and require fix-forward
Drift Handling Console-driven drift detection per stack Drift shown on every plan as diff against refreshed state
Typical Team Fit Application teams co-locating infra with service code Platform or SRE teams managing shared infrastructure across accounts

CI/CD Integration Patterns I Use

For CDK, the modern path is CDK Pipelines or a GitHub Actions workflow that runs npm run build, cdk synth, and cdk deploy --require-approval never with OIDC federation into AWS. The pipeline itself is defined as CDK code, which I appreciate for dogfooding. For Terraform, I run terraform fmt -check, terraform validate, and terraform plan -out plan.file on pull requests, then apply only on merge to main with an approved runner that assumes a deployment role. Both integrate cleanly with policy checks, but Terraform's plan artifact is easier to attach to a pull request for reviewers who want to see exact changes.

Deciding Between CDK and Terraform for Your AWS Architecture Roadmap

There is no universal winner, only the right fit for your constraints. If your organization is all-in on AWS, your developers are comfortable in TypeScript or Python, and you want infrastructure that lives alongside application code with strong testing and refactoring support, CDK accelerates delivery. It is especially effective for serverless and container workloads where you deploy many similar stacks per service or per customer. I have used CDK to model a SaaS tenant isolation pattern where each tenant received its own stack with API Gateway, Lambda, and DynamoDB resources generated from a single construct.

If you need multi-cloud portability, manage infrastructure separately from applications, or your platform team already standardizes on Terraform for networking, DNS, and security tooling, Terraform offers broader coverage and a neutral language that both developers and operators can read. I have seen enterprises succeed by splitting responsibilities: Terraform manages landing zones, VPCs, Transit Gateway, and IAM guardrails, while CDK manages application-level resources inside those accounts. The two tools coexist well as long as you establish clear ownership boundaries and do not try to manage the same resource with both.

A Practical Selection Checklist From Real Deployments

Ask three questions before committing. First, what language does the team that will own the code write daily? If the answer is HCL is new but TypeScript is fluent, CDK lowers onboarding friction. Second, where does state need to live and who will guard it? If you lack a secure, locked remote backend, CDK removes a category of risk. Third, do you need resources outside AWS in the same deployment? If yes, Terraform avoids splitting your toolchain. For beginners, I often recommend starting with Terraform for foundational networking and security baselines, then introducing CDK for service teams building product features. This mirrors a layered architecture where platform concerns are declarative and stable, while application concerns benefit from software engineering patterns.

Finally, consider hiring and long-term maintenance. Terraform skills are widely available among DevOps and SRE candidates, while CDK expertise is concentrated among developers with cloud experience. Both communities are active, but Terraform's registry and documentation provide more examples for edge cases you will encounter when you grow. Whichever you choose, invest in module or construct versioning, automated plan and test gates, and clear documentation so that a new engineer can understand not only what was built, but why it was built that way.

Frequently Asked Questions

Can I use AWS CDK and Terraform together in the same AWS environment?

Yes, and I often do. A common pattern is to let Terraform provision account-level foundations like VPCs, IAM roles, and centralized logging, then use CDK for application stacks that consume outputs such as VPC IDs or subnet IDs via SSM parameters or stack outputs. The key rule is never manage the same resource with both tools, as their state systems are independent and will conflict.

Does AWS CDK support non-AWS resources?

No. CDK synthesizes to CloudFormation, which only provisions AWS resources. If you need to create GitHub repositories, Cloudflare records, or Datadog monitors alongside AWS infrastructure, you will need Terraform or another provider-based tool. You can work around this in CDK with custom resources, but that adds Lambda-backed complexity compared to a native Terraform provider.

Which tool is easier for beginners with no prior IaC experience?

If you already know TypeScript or Python, CDK may feel more approachable because you apply familiar programming concepts. If you are new to both cloud and programming, Terraform's HCL is often simpler to start with because each file is declarative and maps visibly to the AWS console. For complete beginners, I suggest trying Terraform for a single VPC and S3 bucket first, as the plan output teaches you how AWS resources relate.

How does cost differ between CDK and Terraform?

Both tools are free and open source. Costs come from the infrastructure you provision and the operational platforms you choose. CDK deployments incur no extra AWS charge beyond CloudFormation, which is free for resource management. Terraform is free when using the CLI with an S3 backend, while Terraform Cloud has paid tiers for team governance, remote runs, and policy enforcement. Factor in the time cost of maintaining state backends if you self-host Terraform.

Related Articles

References & Standards: Kubernetes Documentation · Docker Documentation · Terraform Documentation