Table of Contents
hide
AWS CloudFormation vs CDK vs Terraform – IaC Comparison
Infrastructure as Code (IaC) enables teams to define, provision, and manage cloud resources through machine-readable configuration files rather than manual console operations. The three dominant IaC tools for AWS are AWS CloudFormation, AWS CDK (Cloud Development Kit), and HashiCorp Terraform. Each takes a fundamentally different approach to solving the same problem — this post provides a comprehensive comparison to help you choose the right tool.
AWS CloudFormation Overview
- AWS CloudFormation is AWS’s native IaC service that provisions and manages AWS resources using declarative JSON or YAML templates.
- CloudFormation templates define the desired state of infrastructure — AWS handles the creation, update, and deletion of resources in the correct order.
- Resources are organized into Stacks, which are the unit of deployment, update, and deletion.
- CloudFormation supports 1,100+ AWS resource types and is tightly integrated with all AWS services.
- Key features include Change Sets (preview changes before applying), Drift Detection, StackSets (multi-account/multi-region deployments), and Nested Stacks.
- IaC Generator (launched Feb 2024) can scan existing AWS resources and generate CloudFormation templates or CDK apps automatically, eliminating weeks of manual effort for brownfield adoption.
- CloudFormation Language Extensions add transforms like
AWS::LanguageExtensionsfor looping, conditionals, and JSON/YAML manipulation — reducing template verbosity. - CloudFormation is free to use — you only pay for the AWS resources provisioned.
AWS CDK Overview
- AWS Cloud Development Kit (CDK) is an open-source framework that lets you define AWS infrastructure using familiar programming languages — TypeScript, JavaScript, Python, Java, C#/.NET, and Go.
- CDK synthesizes your code into CloudFormation templates, then deploys them via CloudFormation — it is an abstraction layer on top of CloudFormation, not a replacement.
- CDK uses a layered construct model:
- L1 (Layer 1) Constructs — Direct 1:1 mapping to CloudFormation resources (prefixed with
Cfn). Verbose but complete. - L2 (Layer 2) Constructs — Curated, high-level abstractions with sensible defaults, helper methods, and security best practices built in. Reduce boilerplate significantly.
- L3 (Layer 3) Constructs / Patterns — Opinionated combinations of multiple resources solving specific use cases (e.g.,
ApplicationLoadBalancedFargateService).
- L1 (Layer 1) Constructs — Direct 1:1 mapping to CloudFormation resources (prefixed with
- CDK v2 consolidates all stable constructs into a single package (
aws-cdk-lib), simplifying dependency management. - CDK Mixins (2026) — Composable abstractions that decouple capabilities from monolithic L2 constructs, allowing you to compose exactly the features you need.
- CDK Refactor (Preview, Sep 2025) — Enables safe infrastructure refactoring (rename constructs, move resources between stacks) while preserving deployed resources.
- CDK Toolkit Library — Programmatic access to CDK operations (synth, deploy, destroy) for advanced CI/CD integration.
- CDK supports unit testing with the
assertionsmodule and compliance checking withcdk-nag.
Terraform Overview
- Terraform by HashiCorp (now IBM) is a multi-cloud IaC tool that uses HashiCorp Configuration Language (HCL) — a declarative language designed specifically for infrastructure.
- Terraform works with providers — plugins that interact with cloud platforms, SaaS tools, and other APIs. The AWS provider covers all AWS services; 4,000+ providers exist in the Terraform Registry.
- Terraform uses a plan → apply workflow:
terraform planshows what will change,terraform applyexecutes the changes. - Terraform maintains its own state file that maps configuration to real-world resources, enabling dependency tracking and change detection.
- Terraform is the only tool of the three that natively supports multi-cloud deployments (AWS, Azure, GCP, etc.) in a single configuration.
- Terraform Stacks (GA late 2025) — Deploy multiple Terraform configurations as a single orchestrated unit with native dependency resolution and progressive rollouts.
- Licensing: In August 2023, HashiCorp changed Terraform’s license from MPL 2.0 to Business Source License (BSL 1.1). IBM acquired HashiCorp in 2024 for $6.4B. This led to OpenTofu, an MPL 2.0-licensed fork maintained by the Linux Foundation (CNCF Sandbox project as of April 2025).
- Terraform Test Framework (native since v1.6) enables unit and integration testing for modules using HCL-based test files.
CDK for Terraform (CDKTF) – Deprecated
- CDKTF (CDK for Terraform) allowed writing Terraform configurations using programming languages (TypeScript, Python, Java, C#, Go) via the CDK construct model, combining CDK’s developer experience with Terraform’s multi-cloud providers.
- ⚠️ CDKTF was deprecated on December 10, 2025. HashiCorp/IBM no longer supports or maintains it. The GitHub repository has been archived.
- Migration options for CDKTF users:
- Terraform HCL — Convert back to native HCL for continued Terraform provider access.
- AWS CDK — If AWS-only, CDK provides a superior programming language experience with active development.
- Pulumi — Multi-cloud IaC with programming language support and Terraform provider compatibility. Offers migration tooling from CDKTF.
- OpenTofu — Open-source Terraform fork (no CDKTF equivalent, HCL only).
- The deprecation of CDKTF eliminated the “best of both worlds” option and forces teams to choose between language flexibility (CDK/Pulumi) and multi-cloud (Terraform HCL).
State Management
- CloudFormation — State is managed entirely by AWS within the CloudFormation service. Each Stack maintains its own state internally. You never manage state files directly — AWS handles consistency, locking, and rollback. State cannot be corrupted or lost by users.
- AWS CDK — Since CDK deploys via CloudFormation, state management is identical to CloudFormation. CDK also maintains a cdk.context.json file for caching environment lookups. No separate state file to manage.
- Terraform — Maintains an explicit state file (
terraform.tfstate) that maps configuration to real infrastructure. State must be stored securely and shared across teams:- Local state — Default; stored on the operator’s filesystem. Not suitable for teams.
- Remote backends — S3 + DynamoDB (locking), Terraform Cloud/Enterprise, GCS, Azure Blob, Consul, etc.
- State file contains sensitive data (resource IDs, outputs) and must be encrypted at rest.
- State locking prevents concurrent modifications that could corrupt state.
- State can be split across workspaces or state files for blast-radius management.
Language Support
| Tool | Language(s) | Notes |
|---|---|---|
| CloudFormation | JSON, YAML | Declarative markup; no loops/conditionals natively (Language Extensions add some). Verbose for complex infrastructure. |
| AWS CDK | TypeScript, JavaScript, Python, Java, C#/.NET, Go | Full programming language power — loops, conditionals, inheritance, composition, IDE support, type safety. |
| Terraform | HCL (HashiCorp Configuration Language) | Domain-specific declarative language. Supports for_each, count, dynamic blocks, functions. Easier to learn than general-purpose languages but less flexible. |
Multi-Cloud Support
- CloudFormation — AWS-only. No support for other cloud providers.
- AWS CDK — Primarily AWS-only. CDK synthesizes to CloudFormation, which only manages AWS resources. Third-party constructs exist for limited non-AWS use cases (e.g., Custom Resources calling external APIs).
- Terraform — True multi-cloud support. A single Terraform configuration can manage resources across AWS, Azure, GCP, Kubernetes, Datadog, GitHub, Cloudflare, and 4,000+ providers simultaneously. This is Terraform’s primary differentiator.
- Organizations with multi-cloud strategies benefit from a unified workflow, language, and state management approach.
- The same HCL language, plan/apply workflow, and module system work identically across all providers.
- OpenTofu — Same multi-cloud capabilities as Terraform (same provider ecosystem) under an open-source license.
Drift Detection
- CloudFormation — Built-in Drift Detection feature. Detects when resource properties differ from the stack template. Can be run on individual resources or entire stacks. Shows IN_SYNC, DRIFTED, or NOT_CHECKED status. Limitation: not all resource properties are checked; only properties defined in the template are compared.
- AWS CDK — Inherits CloudFormation’s drift detection capabilities since CDK deploys via CloudFormation stacks. Use
aws cloudformation detect-stack-drifton synthesized stacks. - Terraform — Drift detection occurs automatically on every
terraform plan. Terraform refreshes the real-world state and compares it to the configuration, showing exactly what has drifted and what changes would be made to remediate. More comprehensive than CloudFormation because:- Detects all property changes, not just template-defined ones.
- Shows the remediation plan immediately.
- Can be automated in CI/CD with scheduled plans.
- Terraform Cloud/Enterprise supports automated drift detection with notifications.
Modules, Constructs, and Nested Stacks
- CloudFormation — Nested Stacks
- Use
AWS::CloudFormation::Stackto embed child stacks within parent stacks. - Templates must be stored in S3 and referenced by URL.
- Useful for reusing common patterns (VPC, security groups) across stacks.
- Outputs from nested stacks can be referenced by parent stacks.
- Limitation: Nested stacks create tight coupling; updates must be initiated from the root stack.
- Stack Exports/Imports — Cross-stack references using
ExportandFn::ImportValuefor loose coupling.
- Use
- AWS CDK — Constructs
- The fundamental building block. Every CDK element is a construct, organized in a tree structure.
- Constructs are composable — you create higher-level constructs from lower-level ones.
- Share constructs via npm, PyPI, Maven, or NuGet packages.
- Construct Hub (construct.dev) — Community registry with 1,500+ published constructs.
- Constructs leverage full programming language capabilities — generics, inheritance, interfaces.
- CDK Mixins (2026) add composable behavior without monolithic construct hierarchies.
- Terraform — Modules
- Modules are reusable packages of Terraform configuration (a directory with .tf files).
- Terraform Registry — 15,000+ published modules for common patterns.
- Modules support versioning, input variables, and output values.
- Can be sourced from local paths, Git repos, S3, GCS, or the Registry.
- Module composition is declarative — modules call other modules.
- Terraform Stacks (GA 2025) orchestrate multiple root modules as a coordinated deployment unit.
Importing Existing Resources
- CloudFormation
- Resource Import — Import existing resources into a stack using
--import-existing-resourcesflag or the console. Must define the resource in the template first, then import. - IaC Generator (2024) — Scans your AWS account, discovers existing resources, identifies relationships, and generates complete CloudFormation templates or CDK apps. Supports targeted resource type scanning. Dramatically simplifies brownfield adoption.
- Supports importing entire applications with resource relationships preserved.
- Resource Import — Import existing resources into a stack using
- AWS CDK
- CDK Migrate — Works with IaC Generator to create CDK apps from existing resources.
- Import existing resources by adding them to the stack with the
importValuemechanism or by using L1 constructs with CloudFormation import. - Can generate CDK code from existing CloudFormation templates using
cdk migrate.
- Terraform
terraform import— Imports existing resources into Terraform state. Requires manually writing the configuration first (or using import blocks since v1.5).- Import Blocks (v1.5+) — Declarative import in configuration files. Can generate configuration with
terraform plan -generate-config-out. - Third-party tools like Terraformer can bulk-import resources and generate HCL.
- Import is per-resource — no automatic relationship detection like CloudFormation’s IaC Generator.
Testing Capabilities
- CloudFormation
- cfn-lint — Linting tool that validates templates against resource specifications.
- TaskCat — Automated testing tool that deploys templates across regions and validates.
- cfn-guard — Policy-as-code tool for validating templates against organizational rules.
- No native unit testing framework — relies on third-party tools or deploying to test accounts.
- AWS CDK
- Assertions module (
aws-cdk-lib/assertions) — Fine-grained unit testing against synthesized CloudFormation templates. Test specific resource properties without deploying. - Snapshot testing — Compare entire synthesized templates against stored snapshots to detect unintended changes.
- cdk-nag — Compliance and security rule packs (AWS Solutions, HIPAA, NIST 800-53) validated at synthesis time using CDK Aspects.
- Uses standard testing frameworks (Jest, pytest, JUnit) — familiar to developers.
- Integration testing —
integ-runnerandinteg-testsconstructs for deploying and validating real infrastructure.
- Assertions module (
- Terraform
- Terraform Test Framework (native since v1.6) — Write test files (
.tftest.hcl) for unit and integration testing of modules. Can create real infrastructure for validation. terraform validate— Syntax and configuration validation without accessing providers.terraform plan— Preview changes; can be used as a validation step in CI.- Terratest (Go library) — Deploy real infrastructure, validate it, then destroy. Popular for integration testing.
- OPA/Sentinel — Policy-as-code for governance (Sentinel is Terraform Enterprise only; OPA works with any plan output).
- tflint — Pluggable linting framework for Terraform.
- Terraform Test Framework (native since v1.6) — Write test files (
CI/CD Integration
- CloudFormation
- Native integration with AWS CodePipeline — deploy/update stacks as pipeline actions.
- Supports StackSets for multi-account/multi-region deployments from a single template.
- Change Sets can be created in a pipeline stage for review before execution.
- Integrates with AWS Service Catalog for standardized deployments.
- Supports Git-based workflows via CodeCommit, CodeBuild, or any CI tool that can call AWS APIs.
- AWS CDK
- CDK Pipelines — High-level construct that defines a self-mutating CI/CD pipeline (pipeline updates itself when you change the pipeline code).
- CDK Toolkit Library enables programmatic deployment from any CI system.
- Synthesized CloudFormation templates can be stored as artifacts and deployed via CodePipeline.
- Standard build tools (npm, pip, Maven) handle compilation and synthesis in CI.
cdk diffin pull requests shows planned infrastructure changes.
- Terraform
- Terraform Cloud/Enterprise — Built-in CI/CD with VCS integration, plan-on-PR, cost estimation, Sentinel policies, and run triggers.
- Integrates with any CI system (GitHub Actions, GitLab CI, Jenkins, CircleCI) via CLI.
terraform planoutput can be posted as PR comments for review.- Atlantis — Popular open-source tool for Terraform PR automation.
- Spacelift, env0, Scalr — Third-party platforms for Terraform CI/CD and governance.
- Remote state and locking enable safe concurrent CI/CD executions.
When to Use Which – Decision Matrix
| Scenario | Recommended Tool | Why |
|---|---|---|
| AWS-only, small team, simple infrastructure | CloudFormation | No additional tools needed; fully managed state; free; tight AWS integration. |
| AWS-only, development team, complex logic | AWS CDK | Programming language power; reusable constructs; unit testing; type safety; rapid iteration. |
| Multi-cloud or hybrid environment | Terraform | Only option for unified multi-cloud IaC; single language across providers. |
| Platform engineering team serving multiple app teams | Terraform | Modules, workspaces, and Stacks enable standardized patterns; HCL is accessible to ops teams. |
| Brownfield — importing many existing AWS resources | CloudFormation/CDK | IaC Generator automatically discovers resources and relationships; far easier than Terraform import. |
| Strict compliance/governance requirements | Terraform Enterprise or CDK + cdk-nag | Sentinel policies (Terraform) or cdk-nag rule packs (CDK) enforce compliance pre-deployment. |
| Open-source licensing requirement | OpenTofu or AWS CDK | Terraform is BSL-licensed; OpenTofu (MPL 2.0) is the open-source alternative. CDK is Apache 2.0. |
| Serverless-first (SAM integration needed) | CloudFormation/CDK | AWS SAM is a CloudFormation extension; CDK supports SAM-like patterns natively with L3 constructs. |
| Kubernetes + cloud infrastructure together | Terraform | Terraform has native Kubernetes, Helm, and cloud providers in a single workflow. |
Detailed Comparison Table
| Feature | CloudFormation | AWS CDK | Terraform |
|---|---|---|---|
| Type | Declarative (JSON/YAML) | Imperative → Declarative (generates CFN) | Declarative (HCL) |
| Cloud Support | AWS only | AWS only | Multi-cloud (4,000+ providers) |
| State Management | Managed by AWS (serverless) | Managed by AWS (via CFN) | Self-managed state file (remote backends) |
| Language | JSON, YAML | TypeScript, Python, Java, C#, Go, JS | HCL |
| Learning Curve | Low (templates) but verbose | Medium (programming + AWS concepts) | Low-Medium (HCL is purpose-built) |
| Drift Detection | Built-in (partial properties) | Via CloudFormation | Automatic on every plan (all properties) |
| Rollback | Automatic on failure | Automatic (via CFN) | No automatic rollback; manual remediation |
| Modularity | Nested Stacks, Stack Exports | Constructs (L1/L2/L3), Mixins | Modules (Registry + custom) |
| Import Resources | Resource Import + IaC Generator | CDK Migrate + IaC Generator | terraform import, import blocks, Terraformer |
| Testing | cfn-lint, cfn-guard, TaskCat | assertions module, cdk-nag, Jest/pytest | terraform test, Terratest, tflint, OPA |
| CI/CD | CodePipeline, StackSets, Change Sets | CDK Pipelines, Toolkit Library | Terraform Cloud, Atlantis, any CI |
| Cost | Free (pay for resources only) | Free (pay for resources only) | CLI free; Cloud/Enterprise paid |
| License | Proprietary (AWS service) | Apache 2.0 | BSL 1.1 (OpenTofu: MPL 2.0) |
| New AWS Service Support | Day-1 (same team) | Day-1 L1; L2 follows weeks later | Days-to-weeks after launch |
| Resource Limit | 500 resources per stack | 500 per stack (same CFN limit) | No hard limit (state file size practical limit) |
| Multi-Account | StackSets | CDK Pipelines cross-account | Provider aliases, workspaces, Stacks |
AWS Certification Exam Practice Questions
- Questions are collected from Internet and the answers are marked as per my knowledge and understanding (which might differ with yours).
- AWS services are updated everyday and both the answers and questions might be outdated soon, so research accordingly.
- Open to further feedback, discussion and correction.
- A company has AWS infrastructure deployed across multiple accounts and regions using manual console operations. They want to bring all existing resources under IaC management with minimal effort. Which approach provides the fastest path to IaC adoption?
- Use Terraform import blocks to import each resource individually and write HCL configuration.
- Use AWS CloudFormation IaC Generator to scan the accounts, discover resources and relationships, and generate CloudFormation templates automatically.
- Write AWS CDK code manually for each resource after documenting the current state.
- Use AWS Config to export resource configurations and convert them to Terraform modules.
- A development team wants to define AWS infrastructure using TypeScript with full IDE support, unit testing, and the ability to use loops and conditionals for dynamic resource creation. They are AWS-only. Which tool best meets their requirements?
- AWS CloudFormation with Language Extensions.
- Terraform with HCL dynamic blocks.
- AWS CDK with TypeScript, using L2 constructs and the assertions module for testing.
- AWS SAM with YAML templates.
- An organization operates across AWS, Azure, and GCP. They need a single IaC tool that can manage resources across all three cloud providers with a unified workflow and state management. Which tool should they use?
- AWS CloudFormation with Custom Resources for Azure and GCP.
- AWS CDK with third-party constructs.
- Separate tools for each cloud provider.
- Terraform (or OpenTofu) with provider configurations for AWS, Azure, and GCP.
- A team using AWS CDK wants to reorganize their infrastructure code by moving resources between stacks and renaming constructs, without replacing the deployed resources. Which CDK feature enables this safe refactoring?
- CDK Pipelines with approval stages.
- CloudFormation Change Sets with manual review.
- CDK Refactor command, which computes mappings between current code and deployed state to preserve resources.
- Export/Import values between stacks with deletion protection.
- A security team needs to ensure all CDK-deployed infrastructure complies with HIPAA requirements before resources are provisioned. Which approach validates compliance at synthesis time without deploying infrastructure?
- Deploy to a test account and run AWS Config rules.
- Use cdk-nag with the HIPAA Security rule pack as a CDK Aspect to validate constructs during synthesis.
- Use CloudFormation drift detection after deployment.
- Write Terraform Sentinel policies.
- A company is evaluating IaC tools and needs automatic rollback capability when a deployment fails partway through creating resources. Which tools provide this natively? (Select TWO)
- AWS CloudFormation
- AWS CDK (via CloudFormation)
- Terraform
- OpenTofu
- Ansible
- An operations team wants continuous drift detection that automatically identifies when infrastructure configuration differs from the declared state. The detection should be comprehensive (all properties, not just template-defined ones) and run on a schedule. Which approach provides the most comprehensive drift detection?
- CloudFormation drift detection on all stacks.
- AWS Config rules for resource compliance.
- Terraform Cloud with scheduled plan-only runs that compare actual state against configuration for all managed properties.
- AWS CDK with snapshot testing in CI/CD.
Related Posts
- AWS CloudFormation
- AWS CloudFormation Best Practices
- AWS CloudFormation Helper Scripts
- AWS Elastic Beanstalk vs OpsWorks vs CloudFormation
- Terraform Cheat Sheet
- HashiCorp Certified Terraform Associate Learning Path
- AWS Management Tools Cheat Sheet