Skip to content

AWS CloudFormation

Introduction

AWS CloudFormation is an Infrastructure as Code (IaC) service that allows you to model, provision, and manage AWS resources using templates. You describe your desired infrastructure in JSON or YAML, and CloudFormation handles the rest.

CloudFormation Overview

Key Features

  • Infrastructure as Code - Version control your infrastructure
  • Declarative - Describe what you want, not how
  • Dependency management - Automatic resource ordering
  • Rollback - Automatic rollback on failures
  • Drift detection - Detect configuration changes
  • Stack sets - Deploy across accounts/regions

When to Use

Ideal Use Cases

  • Repeatable deployments - Same infrastructure in multiple environments
  • Version control - Track infrastructure changes
  • Compliance - Auditable infrastructure definitions
  • Multi-account - StackSets for organization-wide deployment
  • Complex architectures - Many interdependent resources
  • DR/Recovery - Quickly recreate infrastructure

Signs CloudFormation is Right for You

  • Need reproducible infrastructure
  • Want infrastructure versioning
  • Require change tracking and audit
  • Have AWS-only environment
  • Need rollback capabilities

Core Concepts

Templates

  • JSON or YAML files
  • Define resources and configuration
  • Reusable across environments
  • Version controlled

Stacks

  • Collection of resources from a template
  • Single unit of management
  • Create, update, delete together
  • Named and tracked

Change Sets

  • Preview changes before applying
  • See what will be added/modified/deleted
  • Safe way to update stacks

Stack Sets

  • Deploy stacks across accounts/regions
  • Organizational deployment
  • Centralized management

Template Structure

AWSTemplateFormatVersion: "2010-09-09"
Description: My infrastructure template

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

Mappings:
  RegionMap:
    us-east-1:
      AMI: ami-12345678

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

Resources:
  MyEC2Instance:
    Type: AWS::EC2::Instance
    Properties:
      ImageId: !FindInMap [RegionMap, !Ref "AWS::Region", AMI]
      InstanceType: !If [IsProd, t3.large, t3.micro]
      Tags:
        - Key: Name
          Value: !Sub "${Environment}-server"

Outputs:
  InstanceId:
    Value: !Ref MyEC2Instance
    Export:
      Name: !Sub "${Environment}-instance-id"

Template Sections

Section Purpose
Parameters Input values for customization
Mappings Static key-value lookups
Conditions Conditional resource creation
Resources AWS resources to create (required)
Outputs Values to export or display
Transform Macros (e.g., AWS::Serverless)

What to Be Careful About

Template Design

  • Resource limits - 500 resources per stack
  • Circular dependencies - Avoid mutual references
  • Hard-coded values - Use parameters instead
  • Large templates - Consider nested stacks
  • Drift - Resources modified outside CloudFormation

Updates and Changes

  • Replacement vs Update - Some changes require replacement
  • Stack policy - Protect critical resources
  • Rollback triggers - Configure CloudWatch alarms
  • Change sets - Always preview changes

Operations

  • Stack failures - Debug with events, logs
  • Deletion issues - Resources with dependencies
  • IAM permissions - CloudFormation needs permissions
  • S3 storage - Large templates need S3

Cost

  • No direct cost - CloudFormation is free
  • Resources cost - You pay for created resources
  • Failed stacks - May leave billable resources

Intrinsic Functions

Function Purpose Example
!Ref Reference parameter/resource !Ref MyParameter
!Sub String substitution !Sub "${AWS::StackName}-bucket"
!GetAtt Get resource attribute !GetAtt MyEC2.PublicIp
!Join Join strings !Join [",", [a, b, c]]
!If Conditional value !If [IsProd, large, small]
!Equals Compare values !Equals [!Ref Env, prod]
!FindInMap Lookup from mappings !FindInMap [Map, Key1, Key2]
!ImportValue Import from another stack !ImportValue ExportedValue
!Split Split string !Split [",", "a,b,c"]

Common Interview Questions

  1. What is a Change Set?
  2. Preview of changes before execution
  3. Shows adds, modifies, deletes
  4. Safe way to validate updates
  5. Must be executed to apply changes

  6. How do you handle secrets in CloudFormation?

  7. Use AWS::SecretsManager::Secret
  8. Reference with dynamic references: {{resolve:secretsmanager:...}}
  9. Use SSM Parameter Store SecureString
  10. Never hardcode secrets in templates

  11. What happens when a stack update fails?

  12. Automatic rollback to previous state
  13. Failed resources shown in events
  14. Stack status: UPDATE_ROLLBACK_COMPLETE
  15. Can configure rollback triggers (CloudWatch)

  16. What is drift detection?

  17. Detects resources modified outside CloudFormation
  18. Shows actual vs expected configuration
  19. Helps maintain infrastructure consistency
  20. Doesn't auto-fix (just detection)

  21. How do you share resources between stacks?

  22. Outputs/Exports: Export from one stack, import in another
  23. Nested stacks: Child stacks within parent
  24. Cross-stack references: !ImportValue
  25. SSM Parameters: Store values in Parameter Store

Nested Stacks vs Stack Sets

Nested Stacks

  • Stacks within stacks
  • Reusable components
  • Parent manages lifecycle
  • Same account/region
Resources:
  NetworkStack:
    Type: AWS::CloudFormation::Stack
    Properties:
      TemplateURL: https://s3.../network.yaml
      Parameters:
        VpcCidr: 10.0.0.0/16

Stack Sets

  • Deploy across accounts/regions
  • Organizational deployment
  • Centralized management
  • StackSet instances in each target

Helper Scripts

For EC2 instances:

Script Purpose
cfn-init Apply metadata (install packages, create files)
cfn-signal Signal success/failure to CloudFormation
cfn-get-metadata Retrieve metadata
cfn-hup Daemon to detect metadata changes

Example

Resources:
  Instance:
    Type: AWS::EC2::Instance
    Metadata:
      AWS::CloudFormation::Init:
        config:
          packages:
            yum:
              httpd: []
          services:
            sysvinit:
              httpd:
                enabled: true
    CreationPolicy:
      ResourceSignal:
        Timeout: PT5M
    Properties:
      UserData:
        Fn::Base64: !Sub |
          #!/bin/bash
          cfn-init -v --stack ${AWS::StackName} --resource Instance
          cfn-signal -e $? --stack ${AWS::StackName} --resource Instance

Alternatives

AWS Alternatives

Service When to Use Instead
CDK Prefer programming languages
SAM Serverless applications
Proton Platform teams, templates

External Alternatives

Tool Description
Terraform Multi-cloud IaC
Pulumi Multi-cloud, programming languages
Ansible Configuration management
Crossplane Kubernetes-native IaC

Best Practices

  1. Use parameters - Don't hardcode values
  2. Use conditions - Single template for multiple environments
  3. Use nested stacks - Break up large templates
  4. Enable termination protection - Prevent accidental deletion
  5. Use change sets - Preview before updating
  6. Version templates - Git version control
  7. Use stack policies - Protect critical resources
  8. Enable drift detection - Regularly check for drift
  9. Use !Sub over !Join - Cleaner string formatting
  10. Export outputs - Share resources between stacks

Pricing

CloudFormation is free. You only pay for: - Resources created by templates - Handler operations for third-party resources ($0.0009/operation) - Hook operations ($0.00008/operation)