How to Define Infrastructure with CDK and CloudFormation: A Complete Guide

AWS CDK lets you define infrastructure using familiar programming languages like TypeScript or Python, then synthesizes your code into standard CloudFormation templates that deploy via the CDK CLI or AWS CLI.

AWS CDK (Cloud Development Kit) bridges imperative programming and declarative infrastructure by translating code into CloudFormation JSON or YAML. When you define infrastructure with CDK and CloudFormation, you combine the expressive power of software development with the safety and portability of AWS's native provisioning engine. This guide walks through the complete workflow based on the official AWS Agent Toolkit repository.

How CDK Translates Code to CloudFormation

The CDK workflow follows four distinct stages that ultimately generate CloudFormation templates. Understanding this pipeline helps you debug issues and optimize your deployment strategy.

Write constructs first. Each construct is a reusable building block encapsulating one or more AWS resources. CDK provides high-level constructs (e.g., s3.Bucket, lambda.Function) in the aws-cdk-lib package that automatically configure best-practice defaults.

Create a Stack by subclassing cdk.Stack. This groups related constructs and maps directly to a CloudFormation stack during synthesis. According to the repository's CDK skill definition at skills/core-skills/aws-cdk/SKILL.md, stacks represent the unit of deployment in CDK applications.

Synthesize your app with cdk synth. This command traverses your construct tree and emits a CloudFormation template to the cdk.out/ directory. The synthesis process catches type errors and logical inconsistencies before any AWS API calls occur.

Deploy via cdk deploy, which calls the CloudFormation service (aws cloudformation deploy) under the hood. You can also extract the synthesized template and deploy it manually using standard AWS CLI commands.

Setting Up Your CDK Environment

Bootstrapping and Project Setup

Before deploying, you must bootstrap your target AWS account. The cdk bootstrap command creates the CDK toolkit stack (an Amazon S3 bucket and IAM roles) that stores assets during deployment.


# Install the CDK CLI and library

npm install --save-dev aws-cdk
npm install aws-cdk-lib constructs

# Bootstrap the environment (one-time per account/region)

npx cdk bootstrap aws://ACCOUNT_ID/REGION

The repository's bootstrap guide at skills/core-skills/aws-cdk/references/bootstrap-and-project-setup.md details additional configuration options for cdk.json and cross-account scenarios.

Writing Your First Stack

Define infrastructure by extending cdk.Stack and instantiating constructs:

import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as s3 from 'aws-cdk-lib/aws-s3';
import * as lambda from 'aws-cdk-lib/aws-lambda';

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

    const bucket = new s3.Bucket(this, 'MyBucket', {
      versioned: true,
      removalPolicy: cdk.RemovalPolicy.DESTROY,
    });

    new lambda.Function(this, 'MyFunction', {
      runtime: lambda.Runtime.NODEJS_20_X,
      code: lambda.Code.fromAsset('lambda'),
      handler: 'index.handler',
      environment: { BUCKET_NAME: bucket.bucketName },
    });
  }
}

Synthesis and Deployment Commands


# Synthesize CloudFormation template

npx cdk synth

# Deploy via CDK (handles CloudFormation stack creation/update)

npx cdk deploy

# Deploy with hotswap for faster iterative development

npx cdk deploy --hotswap

The deployment reference at skills/core-skills/aws-serverless/references/deployment.md documents flags like --hotswap and --watch for iterative development.

Working with Raw CloudFormation

When to Choose CloudFormation Over CDK

Use plain CloudFormation when you need:

  • Cross-account pipelines requiring static templates checked into version control
  • Compliance-driven environments mandating manual review of YAML/JSON before changes
  • Language-agnostic definitions for teams not using TypeScript, Python, Java, or C#

Writing and Validating Templates

The equivalent CloudFormation YAML for the S3 bucket example above:

AWSTemplateFormatVersion: '2010-09-09'
Resources:
  DemoBucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketEncryption:
        ServerSideEncryptionConfiguration:
          - ServerSideEncryptionByDefault:
              SSEAlgorithm: AES256
      VersioningConfiguration:
        Status: Enabled

Validate templates using cfn-lint for schema validation and cfn-guard for compliance checks:


# Install validation tools

pip install cfn-lint cfn-guard

# Validate syntax and schema

cfn-lint template.yaml

# Check compliance policies

cfn-guard validate -d template.yaml -r rules.guard

The repository's validation SOP at skills/core-skills/aws-cloudformation/references/validate-cloudformation-template.script.md provides detailed interpretation guidance.

Deploying with AWS CLI

aws cloudformation deploy \
  --template-file template.yaml \
  --stack-name MyStack \
  --capabilities CAPABILITY_NAMED_IAM

Key Differences: CDK vs. CloudFormation

Concept CDK CloudFormation
Project bootstrap cdk bootstrap prepares the target account by creating the CDK toolkit stack No bootstrap required; deploy templates directly
Dependency management aws-cdk-lib (v2) is a single npm package; constructs is a peer dependency Dependencies expressed via Resources and Parameters
Validation cdk synth catches type errors; cdk diff shows changes before deployment aws cloudformation validate-template for syntax; cfn-lint for schema
Error diagnostics Use cdk --unstable=diagnose <stack> or inspect CloudFormation events Query CloudFormation events directly with aws cloudformation describe-events --stack-name <stack> --filters FailedEvents=true

The migration guide at skills/core-skills/aws-cdk/references/v1-to-v2-migration.md explains the transition from CDK v1 (@aws-cdk/*) to the consolidated CDK v2 (aws-cdk-lib).

Troubleshooting Failed Deployments

When CDK deployments fail, run the unstable diagnose feature or query events directly:


# CDK diagnosis

cdk --unstable=diagnose MyStack

# CloudFormation event inspection (works for both CDK and raw CFN)

aws cloudformation describe-events \
  --stack-name MyStack \
  --filters FailedEvents=true

For CloudFormation-specific troubleshooting, reference skills/core-skills/aws-cloudformation/references/troubleshoot-deployment.md. For CDK-specific issues, see skills/core-skills/aws-cdk/references/troubleshooting-deployment.md.

Key Repository Reference Files

The AWS Agent Toolkit repository contains authoritative guidance in these locations:

Summary

  • AWS CDK provides programmatic infrastructure definition using TypeScript, Python, Java, or C#, synthesizing to CloudFormation templates via cdk synth and deploying with cdk deploy
  • CloudFormation offers static, declarative templates in YAML/JSON suitable for compliance review and language-agnostic environments
  • Use cdk bootstrap once per account/region to prepare CDK deployment resources
  • Validate CDK apps with cdk diff before deployment; validate raw templates with cfn-lint and cfn-guard
  • Both approaches use CloudFormation as the execution engine, allowing hybrid workflows where you generate templates with CDK, store them in version control, and apply standard CloudFormation compliance checks

Frequently Asked Questions

What is the difference between CDK and CloudFormation?

AWS CDK is a software development framework that generates CloudFormation templates, while CloudFormation is the native AWS service that provisions resources based on JSON or YAML templates. CDK adds abstraction layers, type safety, and programming logic, but ultimately relies on CloudFormation to create resources. You can use CDK for rapid development and reuse, or use raw CloudFormation when you need static templates for compliance review.

Do I need to bootstrap AWS CDK for every deployment?

You only need to run cdk bootstrap once per AWS account and region combination. This command creates the CDK toolkit stack (an S3 bucket and IAM roles) that stores deployment assets like Lambda code bundles and Docker images. After bootstrapping, you can deploy unlimited stacks without repeating this step unless you delete the toolkit stack.

Can I deploy CDK-generated templates using the AWS CLI instead of CDK CLI?

Yes. Run cdk synth to generate the CloudFormation template in the cdk.out/ directory, then deploy it using aws cloudformation deploy or aws cloudformation create-stack. This approach is useful when you need to integrate with existing CI/CD pipelines that expect static template files, or when security policies prohibit the CDK CLI from assuming deployment roles directly.

How do I migrate from CDK v1 to CDK v2?

CDK v2 consolidates all stable constructs into a single package (aws-cdk-lib) instead of the separate @aws-cdk/* packages used in v1. Update your package.json to install aws-cdk-lib and constructs, remove individual v1 packages, and adjust imports to use the new consolidated library structure. Reference the migration guide at skills/core-skills/aws-cdk/references/v1-to-v2-migration.md for breaking changes and step-by-step instructions.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →