AWS Learning Journey

Stop Clicking Around the Console: Infrastructure as Code With CloudFormation

Templates, parameters, mappings, conditions, intrinsic functions, change sets, nested stacks, StackSets, drift detection, and rollbacks — AWS's native way to turn infrastructure into code.

8 min read · 1548 words
AWSCloudFormationInfrastructure As CodeDevOpsCloud Computing
Stop Clicking Around the Console: Infrastructure as Code With CloudFormation cover image

AWS from Zero to Production — Phase 6, Part 1 of 5 · See the full series roadmap


Quick question: if your production AWS account disappeared tonight, how long would it take to rebuild it?

If the honest answer involves screenshots, a wiki page last updated two years ago, and “I think Priya set that up,” you’re not alone. That’s what happens when infrastructure is built by clicking.

Over the last three phases, you built a VPC, load balancers, ECS services, a database, and IAM roles — mostly by hand or with one-off CLI commands. It worked. But you can’t review it, repeat it, version it, or roll it back.

Infrastructure as Code (IaC) fixes that. This phase covers three ways to do it on AWS — CloudFormation, Terraform, and the CDK — starting with the one built into AWS itself.

What you’ll walk away with


Infrastructure as Code principles

The rule that makes it work: once something is managed by code, nobody changes it by hand. Manual changes create drift, and drift breaks trust in the code.


What is CloudFormation?

AWS CloudFormation provisions AWS resources from templates written in YAML or JSON.


Template anatomy

AWSTemplateFormatVersion: "2010-09-09"
Description: Orders API storage bucket

Parameters:
  Environment:
    Type: String
    AllowedValues: [dev, prod]
    Default: dev

Mappings:
  RetentionByEnv:
    dev:
      Days: 7
    prod:
      Days: 90

Conditions:
  IsProd: !Equals [!Ref Environment, prod]

Resources:
  DataBucket:
    Type: AWS::S3::Bucket
    DeletionPolicy: Retain
    Properties:
      BucketName: !Sub "orders-${Environment}-${AWS::AccountId}"
      VersioningConfiguration:
        Status: !If [IsProd, Enabled, Suspended]
      LifecycleConfiguration:
        Rules:
          - Id: expire-old-versions
            Status: Enabled
            NoncurrentVersionExpiration:
              NoncurrentDays: !FindInMap [RetentionByEnv, !Ref Environment, Days]
      PublicAccessBlockConfiguration:
        BlockPublicAcls: true
        BlockPublicPolicy: true
        IgnorePublicAcls: true
        RestrictPublicBuckets: true

Outputs:
  BucketName:
    Value: !Ref DataBucket
    Export:
      Name: !Sub "orders-${Environment}-bucket"

The sections

Resource attributes worth knowing


Intrinsic functions

Intrinsic functions compute values at deploy time:

Pseudo parameters like AWS::AccountId, AWS::Region, and AWS::StackName let templates work in any account and Region without hard-coding.


Creating and updating stacks

aws cloudformation deploy \
  --template-file bucket.yaml \
  --stack-name orders-dev-storage \
  --parameter-overrides Environment=dev

deploy creates the stack if it doesn’t exist, or updates it if it does.

What happens to a resource on update

Each property change has an update behavior, listed in the docs:

Change sets: look before you leap

A change set shows exactly what an update will do before it happens:

aws cloudformation create-change-set \
  --stack-name orders-dev-storage \
  --change-set-name rename-bucket \
  --template-body file://bucket.yaml \
  --parameters ParameterKey=Environment,ParameterValue=dev

aws cloudformation describe-change-set \
  --stack-name orders-dev-storage \
  --change-set-name rename-bucket \
  --query 'Changes[].ResourceChange.[Action,LogicalResourceId,Replacement]'

If you see Replacement: True next to a database, stop and think.

Rule: In production, always review a change set before executing it. aws cloudformation deploy creates one behind the scenes; add --no-execute-changeset to review it first.


Rollback behavior

Rollback triggers can watch CloudWatch alarms during an update and roll back automatically if one fires.


Protecting stacks


Nested stacks

Large templates get unwieldy. Nested stacks split them into reusable pieces:

Resources:
  Network:
    Type: AWS::CloudFormation::Stack
    Properties:
      TemplateURL: https://s3.amazonaws.com/my-templates/network.yaml
      Parameters:
        CidrBlock: 10.0.0.0/16

  Database:
    Type: AWS::CloudFormation::Stack
    Properties:
      TemplateURL: https://s3.amazonaws.com/my-templates/database.yaml
      Parameters:
        SubnetIds: !GetAtt Network.Outputs.DataSubnetIds

The parent stack manages the children as a unit. Use aws cloudformation package to upload local child templates to S3 automatically.

Nested stacks or exports? Nested stacks are deployed together, as one unit. Cross-stack exports link independently deployed stacks — but an exported value can’t change while another stack imports it. Use exports sparingly, for stable values like VPC IDs.


StackSets: one template, many accounts and Regions

StackSets deploy the same stack across many accounts and Regions with one operation:

Typical uses: a baseline IAM role in every account, AWS Config rules, CloudTrail settings, or a security tooling role.


Drift detection

Drift is the difference between what the template says and what’s actually deployed — usually because someone changed something by hand.

aws cloudformation detect-stack-drift --stack-name orders-dev-storage

aws cloudformation describe-stack-resource-drifts \
  --stack-name orders-dev-storage \
  --stack-resource-drift-status-filters MODIFIED DELETED

Fix drift by updating the template to match reality, or by redeploying to restore the template’s settings. Then find out why someone needed to change it by hand.


Linting and testing templates

We’ll add template scanning to the pipeline in Phase 7.


Common mistakes


Key takeaways


Quick self-check

Test yourself before moving on:

  1. What’s the only required section in a CloudFormation template?
  2. How can you find out whether an update will replace your database?
  3. What does DeletionPolicy: Retain do?
  4. You need the same IAM role in 40 accounts. What do you use?

Answers

  1. Resources.
  2. Create and review a change set, and look for Replacement: True.
  3. It keeps the resource when it’s removed from the stack or the stack is deleted.
  4. StackSets, integrated with AWS Organizations.

What’s next

In Part 2, we look at the most popular multi-cloud IaC tool: Terraform — providers, state, remote backends in S3, modules, workspaces, imports, and secrets.

Has a manual change ever broken your CloudFormation stack? Share the story in the comments.


Share this article

LinkedIn post draft