πŸ’‘ Ask Tutor

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

ToolLanguageBest For
CloudFormationYAML / JSONDeclarative templates
AWS CDKTypeScript, Python, Java, GoProgrammatic logic + IaC
TerraformHCLMulti-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

YAML
AWSTemplateFormatVersion: '2010-09-09'
Description: Simple S3 Bucket
Resources:
  MyS3Bucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: my-scriptbuzz-bucket

βœ… Key Sections:

SectionPurpose
ParametersInput values (like region, size)
ResourcesAWS services to be created
OutputsValues to return after stack creation
MappingsRegion or condition-based logic
ConditionsControl resource creation

Deploying a CloudFormation Stack (CLI)

Bash
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:
Bash
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

YAML
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 and Exports 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

  1. Write code using CDK constructs
  2. cdk synth β†’ generates CloudFormation template
  3. cdk deploy β†’ creates/updates stack
  4. 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

Bash
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

FeatureCloudFormationAWS CDK
LanguageYAML/JSONTypeScript, Python, etc.
StyleDeclarativeImperative + declarative hybrid
Learning CurveLowerModerate (code-based abstraction)
ReusabilityLessHigh (constructs, functions)
IDE SupportMinimalFull (intellisense, linting)

βœ… Real-World IaC Use Cases

ScenarioTool
Provision EC2 + S3 for dev/testCloudFormation
Build complex app with multiple stacksCDK
CI/CD pipeline infrastructureCDK + CodePipeline
Multi-account VPC deploymentCloudFormation StackSets
Parameterized RDS provisioningCloudFormation
App hosting with Lambda + API GWCDK