Catalog My learning Blog
AWS Tutorial for Developers: From Account to Production · Phase 4 · Lesson 24 · 3 min read

AWS CloudFormation Tutorial: Infrastructure as Code

On this page
  1. Why infrastructure as code
  2. CloudFormation templates and stacks
  3. Previewing changes with a CloudFormation change set
  4. CloudFormation guard rails
  5. CloudFormation vs CDK vs Terraform
  6. Check yourself

Why infrastructure as code

A VPC, subnets, security groups, a load balancer, an Auto Scaling group, a database: built by hand in the console, nobody can review it, repeat it for staging, or tell what changed last Tuesday. Infrastructure as code describes it in files that live in Git, get reviewed in pull requests, and are applied by a tool. CloudFormation is AWS's built-in one.

CloudFormation templates and stacks

A template (YAML or JSON) declares resources and how they connect. Deploying it creates a stack: CloudFormation works out the order from the dependencies, creates everything, and rolls back if anything fails. Updating the template updates the stack; deleting the stack deletes its resources.

YAML
AWSTemplateFormatVersion: "2010-09-09"
Description: One app server, sized by a parameter

Parameters:
  InstanceType:
    Type: String
    Default: m7g.large
    AllowedValues: [m7g.large, r7g.large]
  ImageId:
    Type: AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>
    Default: /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-arm64

Resources:
  AppServer:
    Type: AWS::EC2::Instance
    Properties:
      InstanceType: !Ref InstanceType
      ImageId: !Ref ImageId
      MetadataOptions:
        HttpTokens: required
      Tags:
        - Key: Name
          Value: app-server

Outputs:
  InstanceId:
    Value: !Ref AppServer
  • Parameters make one template work for several environments.
  • The ImageId parameter reads the latest Amazon Linux AMI from a public SSM parameter at deploy time, so no AMI ID is hardcoded.
  • !Ref and !GetAtt wire resources together; Outputs expose values to people and other stacks.

Lint before deploying. cfn-lint checks resource types, properties and values against the CloudFormation specification; this template passes cleanly:

Code
cfn-lint app-server.yaml && echo lint-clean
Code
lint-clean

Previewing changes with a CloudFormation change set

Updating a stack directly is risky: some property changes replace a resource, meaning delete and recreate it, which for a database means losing data. A change set shows what will happen first:

Shell
aws cloudformation create-change-set --stack-name app-server \
  --change-set-name resize-to-r7g \
  --use-previous-template \
  --parameters ParameterKey=InstanceType,ParameterValue=r7g.large ParameterKey=ImageId,UsePreviousValue=true

aws cloudformation describe-change-set --stack-name app-server \
  --change-set-name resize-to-r7g \
  --query 'Changes[].ResourceChange.[Action,LogicalResourceId,ResourceType,Replacement]' --output text

For an instance type change on an EBS-backed instance, the real service reports Modify AppServer AWS::EC2::Instance False: an in-place update that stops and starts the instance. Changing ImageId instead would show Replacement True, a new instance. Read the Replacement column every time, then execute-change-set once you're happy.

A template becomes a stack; a change set previews which resources will be modified, replaced or left alone before you apply it.
A template becomes a stack; a change set previews which resources will be modified, replaced or left alone before you apply it.

CloudFormation guard rails

  • DeletionPolicy: Retain or Snapshot on databases and buckets, and stack termination protection, so a mistaken delete doesn't destroy data.
  • Drift detection finds resources someone changed by hand outside CloudFormation.
  • Stack policies block updates to critical resources.
  • Nested stacks or StackSets for reuse across stacks, accounts and regions.

CloudFormation vs CDK vs Terraform

ToolWhat you writeNotes
CloudFormationYAML or JSONAWS-native, no state file to manage, new AWS features usually supported quickly
AWS CDKTypeScript, Python, Java, C#, GoReal code with loops and classes, compiled into CloudFormation
Terraform / OpenTofuHCLWorks across clouds and SaaS providers; you manage a state file

All three beat the console. Pick one per team and use it for everything, so there's one source of truth.

Check yourself

It previews every change before anything happens, including resources that would be replaced rather than updated, which for a database means a new, empty instance. You review it, then execute or discard it.

Set DeletionPolicy: Retain or Snapshot on the database resource, plus UpdateReplacePolicy, and enable termination protection on the stack so it can't be deleted until someone turns that off.

Drift detection compares each resource's actual configuration with what the template declares and reports the differences. Fix it by updating the template or reverting the manual change, then make console changes rare.

When you want loops, functions and reusable components in a real programming language. CDK still synthesizes CloudFormation, so stacks and change sets work the same.

Networking, databases and applications change at different rates. Separate stacks limit the impact of a mistake and make updates faster and safer.