Infrastructure as Code (IaC) with AWS CloudFormation and AWS CDK
Automate, Standardize, and Scale Your Cloud Infrastructure
Managing cloud resources manually is inefficient and error-proneβespecially at scale. With Infrastructure as Code (IaC), you can define, provision, and update AWS infrastructure using code, making deployments repeatable, testable, and version-controlled.
This chapter dives into:
- CloudFormation (YAML/JSON templates)
- AWS CDK (Cloud Development Kit using TypeScript, Python, etc.)
- Real-world use cases, best practices, and CLI commands
π What is Infrastructure as Code (IaC)?
IaC is the practice of managing and provisioning infrastructure through machine-readable configuration files, rather than through physical hardware or manual configuration.
Benefits of IaC:
- β Automation & Repeatability
- β Version control via Git
- β Easy collaboration in teams
- β Fast provisioning of complete environments
- β Lower risk of human error
π§± AWS IaC Options Comparison
Tool | Language | Best For |
---|---|---|
CloudFormation | YAML / JSON | Declarative templates |
AWS CDK | TypeScript, Python, Java, Go | Programmatic logic + IaC |
Terraform | HCL | Multi-cloud, more flexible (3rd-party) |
π This chapter focuses on CloudFormation and CDK, both native to AWS.
Section 1: AWS CloudFormation β Declarative IaC
π What is CloudFormation?
AWS CloudFormation is a service that enables you to describe your AWS infrastructure using YAML or JSON templates.
You can deploy:
- EC2 instances
- S3 buckets
- VPCs, IAM roles, Lambda functions, RDS databases, etc.
- Entire architectures with dependencies, conditions, and outputs
π CloudFormation Template Structure
AWSTemplateFormatVersion: '2010-09-09'
Description: Simple S3 Bucket
Resources:
MyS3Bucket:
Type: AWS::S3::Bucket
Properties:
BucketName: my-scriptbuzz-bucket
β Key Sections:
Section | Purpose |
---|---|
Parameters | Input values (like region, size) |
Resources | AWS services to be created |
Outputs | Values to return after stack creation |
Mappings | Region or condition-based logic |
Conditions | Control resource creation |
Deploying a CloudFormation Stack (CLI)
aws cloudformation create-stack \
--stack-name my-s3-stack \
--template-body file://template.yaml \
--capabilities CAPABILITY_NAMED_IAM
π§ Use CAPABILITY_NAMED_IAM
when IAM roles or policies are included in the template.
π Updating a Stack
- Change your YAML template
- Run:
aws cloudformation update-stack \
--stack-name my-s3-stack \
--template-body file://template.yaml
CloudFormation automatically handles diffing, replacement, or in-place updates.
Real-World Use Case
Multi-Tier Web App Deployment
Resources:
WebServer:
Type: AWS::EC2::Instance
Properties:
InstanceType: t2.micro
ImageId: ami-0abcdef1234567890
SecurityGroups:
- Ref: WebServerSG
WebServerSG:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Allow HTTP
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 80
ToPort: 80
CidrIp: 0.0.0.0/0
π‘ Use nested stacks for modularity (VPC, EC2, RDS as separate templates).
Best Practices for CloudFormation
- Use YAML over JSON for readability
- Keep templates modular and reusable
- Use
Outputs
andExports
to share values between stacks - Parameterize for environment-specific values (e.g.,
Env=dev
) - Use change sets to preview updates before applying
- Version templates in Git
Section 2: AWS CDK β Programmatic IaC with Familiar Languages
π What is AWS CDK?
AWS Cloud Development Kit (CDK) allows you to define AWS infrastructure using real programming languages:
- TypeScript (recommended)
- Python
- Java
- Go
- C#
The CDK compiles your code into a CloudFormation template, which is then deployed.
CDK Workflow
- Write code using CDK constructs
cdk synth
β generates CloudFormation templatecdk deploy
β creates/updates stack- Infrastructure is live on AWS
π§ Example CDK App (TypeScript)
import * as cdk from 'aws-cdk-lib';
import { Bucket } from 'aws-cdk-lib/aws-s3';
class MyStack extends cdk.Stack {
constructor(scope: cdk.App, id: string) {
super(scope, id);
new Bucket(this, 'MyBucket', {
versioned: true,
bucketName: 'my-scriptbuzz-cdk-bucket'
});
}
}
const app = new cdk.App();
new MyStack(app, 'ScriptBuzzStack');
CDK CLI Commands
cdk init app --language typescript
npm install aws-cdk-lib constructs
cdk synth # Generate CloudFormation template
cdk deploy # Deploy stack to AWS
cdk destroy # Delete stack
π CDK Constructs & Reusability
CDK uses constructs as building blocks.
- Level 1 (L1): direct CloudFormation mappings
- Level 2 (L2): opinionated, simplified versions
- Level 3 (L3): high-level reusable patterns
β You can publish your own CDK packages and reuse them across teams.
CDK Best Practices
- Use context values for environment-specific customization
- Store secrets in SSM Parameter Store or Secrets Manager
- Use constructs for encapsulation
- Use Git for versioning + CI/CD integration
- Combine CDK with CodePipeline for continuous deployment
Summary: CloudFormation vs CDK
Feature | CloudFormation | AWS CDK |
---|---|---|
Language | YAML/JSON | TypeScript, Python, etc. |
Style | Declarative | Imperative + declarative hybrid |
Learning Curve | Lower | Moderate (code-based abstraction) |
Reusability | Less | High (constructs, functions) |
IDE Support | Minimal | Full (intellisense, linting) |
β Real-World IaC Use Cases
Scenario | Tool |
---|---|
Provision EC2 + S3 for dev/test | CloudFormation |
Build complex app with multiple stacks | CDK |
CI/CD pipeline infrastructure | CDK + CodePipeline |
Multi-account VPC deployment | CloudFormation StackSets |
Parameterized RDS provisioning | CloudFormation |
App hosting with Lambda + API GW | CDK |
π‘ Explore More AWS Tools & Resources
Educational AI Tutor
Get instant AWS-related answers and explanations using AI.
Interview Question Generator
Generate AWS interview questions for practice and preparation.
AWS Practice Quiz
Test your AWS knowledge with timed quizzes and scoring.
AWS Interview Questions
Browse frequently asked AWS interview questions with answers.