AWS Cloud Practitioner Study Notes · Part 35

AWS CloudFormation: Templates, Stacks, Rollbacks, and Change Safety

AWS Cloud Practitioner study notes explaining CloudFormation templates, stacks, parameters, outputs, policies, StackSets, drift, and change sets.

AWS CloudFormation lets you define AWS infrastructure as code. Instead of manually creating a VPC, subnets, security groups, EC2 instances, load balancers, and databases in the console, you describe the desired resources in a YAML or JSON template and deploy them as a managed stack.

This is Part 35 of the AWS Cloud Practitioner Study Notes. Part 33 explained the EC2 and Auto Scaling architecture that CloudFormation can provision, while Part 34 covered the load balancers commonly defined inside an infrastructure stack.

What problem does CloudFormation solve?

Manual console deployment is difficult to repeat consistently:

Click → configure → remember the setting → repeat in another Region

CloudFormation turns the architecture into a versioned template:

Git repository


CloudFormation template


CloudFormation stack


Repeatable AWS resources

This is Infrastructure as Code (IaC). Templates can be reviewed, tested, changed through pull requests, and deployed through CI/CD. CloudFormation is AWS-native, so it is particularly useful when the target environment is primarily AWS.

Template and stack

A template is the YAML or JSON definition of the desired infrastructure. A stack is the deployed collection of resources that CloudFormation manages from that template.

Template
  ├── VPC
  ├── Subnets
  ├── Security groups
  ├── EC2 / Auto Scaling
  ├── Load balancer
  └── RDS


      Stack

You create, update, and delete the resources through stack operations rather than treating every resource as an unrelated manual object. CloudFormation tracks the logical resources and their relationships, while AWS services create the physical resources.

A minimal template

The Resources section is the core of every useful template:

AWSTemplateFormatVersion: '2010-09-09'
Description: A small EC2 example

Resources:
  WebServer:
    Type: AWS::EC2::Instance
    Properties:
      InstanceType: t3.micro
      ImageId: ami-xxxxxxxxxxxxxxxxx

The logical ID WebServer identifies the resource inside the template. The resource type tells CloudFormation which AWS service resource to create. The properties configure it.

CloudFormation template sections

SectionPurpose
AWSTemplateFormatVersionIdentifies the template format version when specified
DescriptionExplains what the template deploys
ParametersAccept deployment-time input values
MappingsStore static key-value mappings, often Region-specific values
ConditionsDecide whether resources or properties are included
ResourcesDefine the AWS resources to create; required
OutputsReturn useful values such as IDs, endpoints, or URLs

Not every section is required. Resources is the required section that defines what CloudFormation provisions.

Parameters: customise without editing the template

Parameters let users provide values when creating or updating a stack:

Parameters:
  InstanceType:
    Type: String
    Default: t3.micro
    AllowedValues:
      - t3.micro
      - t3.small
      - m7i.large

The same template can then be used for a small development instance or a larger environment without changing the source file. Parameters are useful for environment names, CIDR ranges, instance classes, and other deployment choices.

Outputs: expose useful values

Outputs return values after a stack operation. They can expose resource IDs, DNS names, or values that another stack or operator needs:

Outputs:
  WebsiteURL:
    Description: Load balancer DNS name
    Value: !GetAtt ApplicationLoadBalancer.DNSName

After deployment, an operator can use the output rather than searching through several AWS console pages for the load balancer endpoint.

Stack lifecycle and rollback

Typical stack events include:

CREATE_IN_PROGRESS


CREATE_COMPLETE

UPDATE_IN_PROGRESS → UPDATE_COMPLETE

DELETE_IN_PROGRESS → DELETE_COMPLETE

CloudFormation creates resources in an order based on dependencies. If a resource fails during creation, the stack normally rolls back the resources that it created so that a failed deployment does not leave a partially provisioned environment behind.

For example, if a database fails after the network and application resources were created, CloudFormation can remove the resources created during that operation, subject to resource policies and the final stack configuration.

Rollback is useful, but it is not a substitute for testing templates, reviewing permissions, checking quotas, and protecting data resources.

Resource dependencies

CloudFormation automatically detects many dependencies when one resource references another. For example, a security group reference can tell CloudFormation that the group must exist before the dependent resource.

When the dependency is not visible through a reference, use DependsOn:

MyRoute:
  Type: AWS::EC2::Route
  DependsOn: InternetGatewayAttachment
  Properties:
    RouteTableId: !Ref PublicRouteTable
    DestinationCidrBlock: 0.0.0.0/0
    GatewayId: !Ref InternetGateway

Use explicit dependencies only when needed. Overusing them can make a stack slower and more tightly coupled than necessary.

CreationPolicy and cfn-signal

An EC2 instance reaching the running state only proves that the virtual machine has started. It does not prove that packages are installed or that the application is ready.

For EC2 and Auto Scaling resources, CloudFormation recommends a CreationPolicy with cfn-signal. The flow is:

Launch EC2


User data runs


Install and configure application


cfn-signal reports success


CloudFormation marks resource complete

A simplified example is:

WebServer:
  Type: AWS::EC2::Instance
  CreationPolicy:
    ResourceSignal:
      Count: 1
      Timeout: PT10M
  Properties:
    UserData:
      Fn::Base64: !Sub |
        #!/bin/bash -xe
        # Install and configure the application here
        /opt/aws/bin/cfn-signal \
          --exit-code $? \
          --stack ${AWS::StackName} \
          --resource WebServer \
          --region ${AWS::Region}

In a real script, run the application setup first, capture its result, and call cfn-signal with success only when the setup completed correctly. If the required signal is not received before the timeout, the resource creation fails and the stack can roll back.

WaitCondition versus CreationPolicy

WaitCondition and WaitConditionHandle are older coordination mechanisms that use signals and a presigned URL. They remain useful for some external coordination cases, but AWS recommends CreationPolicy and cfn-signal for EC2 and Auto Scaling resources.

EC2 or Auto Scaling resource → CreationPolicy + cfn-signal
Other external coordination  → WaitCondition may be appropriate

CloudFormation helper scripts

CloudFormation provides helper scripts for bootstrapping instances:

  • cfn-init: reads AWS::CloudFormation::Init metadata and applies packages, files, commands, and services.
  • cfn-signal: tells CloudFormation whether resource configuration succeeded.
  • cfn-hup: detects metadata changes and can trigger configuration actions.

A common setup is:

cfn-init → install packages and configure files


cfn-signal → report success or failure

UpdatePolicy and rolling updates

When an Auto Scaling group uses a new AMI or launch configuration, replacing every instance at once may cause an outage. UpdatePolicy can control how CloudFormation performs rolling updates, including the batch size, pause time, and whether it waits for resource signals.

Update instance 1


Health check and signal pass


Update instance 2

This is useful for gradually replacing application instances while maintaining capacity. The exact update behaviour depends on the resource type and the policy settings.

DeletionPolicy: protect important data

Deleting a stack normally deletes the resources that CloudFormation manages, but stateful resources need special care. DeletionPolicy: Retain keeps a resource when the stack is deleted:

ProductionDatabase:
  Type: AWS::RDS::DBInstance
  DeletionPolicy: Retain

This is useful for important RDS databases, S3 buckets, or other resources whose data must outlive the application stack. Retain does not create a backup or remove the resource from your responsibility; the retained resource continues to exist and may continue to incur charges.

Other deletion and update policies, such as Snapshot, may be appropriate for supported resources. Always review the resource’s update and deletion behaviour before changing a production stack.

Change sets: preview an update

A change set lets you preview a proposed stack update before executing it. CloudFormation shows resources that will be added, modified, replaced, or deleted.

New template


Create change set


Review create / modify / replace / delete


Execute only after approval

Change sets reduce the risk of surprising replacements, especially for databases, network resources, and security controls. They do not guarantee that the update will succeed because runtime conditions such as service quotas, permissions, and service-specific constraints can still cause failure.

Drift detection

Drift occurs when a resource managed by CloudFormation is changed outside CloudFormation—for example, someone changes a security group in the console.

Template definition ≠ actual AWS configuration


                   Configuration drift

Drift detection compares the expected properties in the template and parameters with the actual resource configuration for supported resource types. It helps identify changes that should be reconciled, reverted, or intentionally incorporated into the template.

Drift detection does not automatically fix every difference, and unsupported resource types or properties may be reported as not checked. It is a visibility and governance feature, not an automatic replacement for source control.

Nested stacks

Large templates can be divided into reusable child templates:

Parent stack
├── Networking nested stack
├── Database nested stack
└── Application nested stack

Nested stacks help separate concerns and reduce the size of a parent template. They are still managed as part of the parent stack, so understand the ownership and update relationships before changing or deleting child resources.

StackSets

StackSets deploy the same CloudFormation template to multiple AWS accounts and Regions. They are useful for organisation-wide resources such as logging, security baselines, IAM roles, or standard networking components.

StackSet template
├── Account A / Region 1
├── Account B / Region 1
├── Account A / Region 2
└── Account C / Region 3

You can customise individual stack instances with parameters while keeping the template consistent. StackSets are the answer when the requirement is centralised deployment across accounts or Regions.

Complete CloudFormation workflow

1. Write YAML or JSON template
2. Store it in version control
3. Validate syntax and resource definitions
4. Create or update a stack
5. CloudFormation creates resources in dependency order
6. User data and helper scripts configure instances
7. CreationPolicy receives cfn-signal when ready
8. CloudFormation reports stack status
9. Review outputs and stack events
10. Use change sets for future updates
11. Check drift when out-of-band changes are suspected

For a production workflow, add code review, least-privilege deployment roles, linting, policy checks, change-set approval, failure notifications, and backup or retention policies for stateful resources.

CloudFormation versus Terraform

FeatureCloudFormationTerraform
Primary scopeAWSAWS and many other providers
Template languageYAML or JSONHCL
Main deployment unitStackConfiguration and state
AWS integrationNative AWS serviceProvider-based
Multi-platform infrastructureLimited to supported AWS ecosystemBroad provider ecosystem

CloudFormation is a natural choice for AWS-only environments and integrates directly with AWS resource types and stack operations. Terraform can be a better fit when one workflow manages AWS, Azure, GCP, Kubernetes, SaaS services, or other platforms. Both are Infrastructure as Code tools; the decision depends on scope, team practice, and required provider ecosystem.

Common exam questions

ScenarioLikely answer
Provision AWS infrastructure from YAML or JSONCloudFormation
Manage related AWS resources as one unitCloudFormation stack
Deploy the same template across accounts and RegionsStackSets
Preview resource changes before applying an updateChange set
Keep an RDS database after stack deletionDeletionPolicy: Retain
Wait for an EC2 application to finish bootstrappingCreationPolicy with cfn-signal
Detect manual changes made outside CloudFormationDrift detection
Split a large template into reusable componentsNested stacks
Configure explicit resource creation orderDependsOn
Roll instances through an Auto Scaling updateUpdatePolicy

Common exam traps

Template versus stack

A template is the definition. A stack is the deployed collection of resources created from that definition.

Change sets versus rollback

A change set previews a proposed update before execution. Rollback responds to a failed operation by restoring resources where possible. A change set does not guarantee that execution will succeed.

CreationPolicy versus EC2 running state

running means the virtual machine has started. CreationPolicy plus cfn-signal can wait for application configuration to finish.

DeletionPolicy versus backup

Retain leaves the resource in AWS when the stack is deleted. It does not create a backup, replicate the data, or test restore procedures.

Drift detection versus automatic reconciliation

Drift detection identifies differences. It does not automatically decide whether to update the template, revert the resource, or preserve the manual change.

Memory map for CLF-C02

  • Need infrastructure as code? → CloudFormation
  • Need a group of managed resources? → Stack
  • Need input values? → Parameters
  • Need resource IDs or endpoints? → Outputs
  • Need preview before an update? → Change set
  • Need deploy to many accounts or Regions? → StackSets
  • Need keep a database after stack deletion? → DeletionPolicy: Retain
  • Need wait until EC2 setup completes? → CreationPolicy + cfn-signal
  • Need detect console changes? → Drift detection
  • Need reusable template modules? → Nested stacks

Conclusion

CloudFormation is more than a template format. It is a stack-based deployment system that creates, updates, tracks, and deletes related AWS resources as a unit. Parameters and outputs make templates reusable; dependency and update policies control ordering and change behaviour; change sets and drift detection improve safety; StackSets extend the same infrastructure pattern across accounts and Regions.

The most useful exam rule is: CloudFormation defines infrastructure, stacks manage it, change sets preview it, rollback protects failed operations, and drift detection reveals changes made outside the template. For EC2 bootstrapping, use CreationPolicy and cfn-signal when “instance running” is not the same as “application ready”.

Sources

Back to the journal