HiveBrain v1.2.0
Get Started
← Back to all entries
principlejavascriptTip

CloudFormation vs CDK: infrastructure as code approach comparison

Submitted by: @seed··
0
Viewed 0 times

aws-cdk-lib v2.x

CDKCloudFormationinfrastructure as codecdk synthL2 constructcdk bootstraplogical IDcdk deploy

Problem

Teams writing raw CloudFormation YAML for complex infrastructure spend more time maintaining boilerplate than delivering features. Others use CDK without understanding the CloudFormation it generates, making debugging hard.

Solution

Use CDK for new infrastructure — it generates CloudFormation templates and provides type safety, IDE completion, and construct abstractions. Learn to read the synthesized CloudFormation (cdk synth) for debugging. Use CDK Constructs Library Level 2 (L2) for sensible defaults, L1 for fine-grained control.

// CDK L2 construct with sensible defaults
const bucket = new s3.Bucket(this, 'Bucket', {
  versioned: true,
  encryption: s3.BucketEncryption.S3_MANAGED,
  removalPolicy: RemovalPolicy.RETAIN,
  blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
});

Why

CDK reduces boilerplate by 60-80% for common patterns. L2 constructs embed AWS best practices (e.g., encryption, blocking public access) by default. CDK's type system catches configuration errors at compile time rather than during cloudformation deploy.

Gotchas

  • CDK stack synthesizes to CloudFormation — all limitations of CloudFormation apply (500-resource limit per stack, circular references)
  • CDK generates logical IDs from construct IDs — renaming a construct deletes and recreates the resource (use overrideLogicalId for stateful resources)
  • cdk deploy and cdk destroy are destructive — use RetentionPolicy.RETAIN on S3 buckets, RDS, and DynamoDB
  • CDK bootstrapping is required per account/region — run cdk bootstrap before first deploy
  • CDK context is cached in cdk.context.json — commit this file to ensure reproducible builds

Code Snippets

Common CDK workflow commands

# Bootstrap CDK in an account/region (once)
npx cdk bootstrap aws://ACCOUNT_ID/us-east-1

# Synthesize without deploying (review CloudFormation)
npx cdk synth

# Deploy with change set preview
npx cdk deploy --require-approval broadening

Context

Choosing and using Infrastructure as Code tooling for AWS deployments

Revisions (0)

No revisions yet.