CloudFormation & CDK
Infrastructure as Code — define your entire AWS infrastructure in TypeScript or YAML, version-controlled and reproducible
Skills taught: aws.cloudformation, aws.cdk, aws.iac, aws.stacks, aws.constructs, aws.cdk-deploy
Why Infrastructure as Code?
Clicking through the AWS console to create resources is fine for learning. In production, it's a liability: no audit trail, hard to reproduce, easy to make mistakes, impossible to diff between environments. Infrastructure as Code (IaC) solves this by describing your infrastructure in code files — versioned in git, reviewed in PRs, automatically applied. Destroying and recreating an entire environment takes minutes, not days.
CloudFormation — AWS native IaC
AWSTemplateFormatVersion: '2010-09-09'
Description: Static website hosting with S3 and CloudFront
Parameters:
DomainName:
Type: String
Description: Domain name for the website
Default: myapp.com
Resources:
# S3 bucket for website content
WebsiteBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !Sub '${DomainName}-website'
PublicAccessBlockConfiguration:
BlockPublicAcls: true
BlockPublicPolicy: true
IgnorePublicAcls: true
RestrictPublicBuckets: true
# SSL certificate (must be us-east-1 for CloudFront)
Certificate:
Type: AWS::CertificateManager::Certificate
Properties:
DomainName: !Ref DomainName
ValidationMethod: DNS
# CloudFront distribution
Distribution:
Type: AWS::CloudFront::Distribution
Properties:
DistributionConfig:
DefaultRootObject: index.html
Enabled: true
Origins:
- Id: S3Origin
DomainName: !GetAtt WebsiteBucket.RegionalDomainName
DefaultCacheBehavior:
TargetOriginId: S3Origin
ViewerProtocolPolicy: redirect-to-https
Compress: true
ViewerCertificate:
AcmCertificateArn: !Ref Certificate
SslSupportMethod: sni-only
Outputs:
DistributionURL:
Value: !GetAtt Distribution.DomainName
Description: CloudFront URL
# Deploy:
# aws cloudformation deploy --template-file template.yml --stack-name myapp-website
AWS CDK — CloudFormation in TypeScript
import * as cdk from 'aws-cdk-lib';
import * as s3 from 'aws-cdk-lib/aws-s3';
import * as cloudfront from 'aws-cdk-lib/aws-cloudfront';
import * as origins from 'aws-cdk-lib/aws-cloudfront-origins';
import * as s3deploy from 'aws-cdk-lib/aws-s3-deployment';
export class WebsiteStack extends cdk.Stack {
constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
super(scope, id, props);
// S3 bucket for website files
const bucket = new s3.Bucket(this, 'WebsiteBucket', {
removalPolicy: cdk.RemovalPolicy.DESTROY, // delete bucket when stack is deleted
autoDeleteObjects: true,
blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
});
// CloudFront distribution
const distribution = new cloudfront.Distribution(this, 'Distribution', {
defaultBehavior: {
origin: origins.S3BucketOrigin.withOriginAccessControl(bucket),
viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
compress: true,
},
defaultRootObject: 'index.html',
errorResponses: [
// SPA routing: 404 → serve index.html (React Router handles it)
{ httpStatus: 404, responseHttpStatus: 200, responsePagePath: '/index.html' },
],
});
// Deploy website files from local dist/ directory
new s3deploy.BucketDeployment(this, 'DeployWebsite', {
sources: [s3deploy.Source.asset('./dist')],
destinationBucket: bucket,
distribution,
distributionPaths: ['/*'], // invalidate CloudFront cache on deploy
});
// Outputs
new cdk.CfnOutput(this, 'URL', {
value: `https://${distribution.distributionDomainName}`,
});
}
}
// bin/app.ts
const app = new cdk.App();
new WebsiteStack(app, 'MyAppWebsite', {
env: { region: 'us-east-1' },
});
# Install CDK
npm install -g aws-cdk
npm install aws-cdk-lib constructs
# Bootstrap (one-time per account/region setup)
cdk bootstrap aws://123456789012/us-east-1
# Preview changes (like terraform plan)
cdk diff
# Output: shows what will be created, modified, or deleted
# Deploy
cdk deploy
# Creates/updates the CloudFormation stack
# Destroy all resources
cdk destroy
# Synthesize CloudFormation template (see what CDK generates)
cdk synth
Tip: CDK is CloudFormation with superpowers. CDK compiles to CloudFormation YAML under the hood — cdk synth shows you exactly what CloudFormation template it generates. You get all CloudFormation's reliability and state management, plus the ability to use TypeScript: loops to create multiple similar resources, abstractions (Constructs), type-safe props, and reusable patterns shared as npm packages.
Frequently Asked Questions
CDK vs Terraform — which should I learn?
Both are excellent. CDK is AWS-only but lets you use TypeScript. Terraform is multi-cloud (AWS, GCP, Azure) with its own HCL language. For AWS-only projects: CDK gives better type safety and access to all new AWS services immediately (no waiting for provider updates). For multi-cloud or existing Terraform organizations: Terraform. Many teams use both: CDK for application infrastructure, Terraform for org-level resources.