Lesson 1 of 5 AWS CloudFormation

Understanding Templates and Stacks in CloudFormation

AWS CloudFormation creates and manages AWS resources from declarative templates. A template describes the desired state; CloudFormation works out the order of operations, creates the resources and tracks them as a single unit called a stack. This lesson explains every section of a template, the intrinsic functions and pseudo parameters used to make templates reusable, and the lifecycle of a stack.

Learning outcomes

After completing this lesson, you will be able to:

  • Describe the sections of a CloudFormation template and the purpose of each.
  • Explain how intrinsic functions, pseudo parameters and parameter types make a template reusable across environments.
  • Explain how CloudFormation determines the order of resource operations, including implicit and explicit dependencies.
  • Describe the stack lifecycle, stack statuses, default rollback behaviour and the role of capabilities and service roles.

Declarative Infrastructure

A CloudFormation template is a JSON or YAML document that declares resources and their properties. It does not list steps; it states what should exist. When a template is submitted, CloudFormation compares it with what the stack already contains and makes the API calls needed to reach the declared state. The set of resources created from one template is a stack, and the stack is the unit of creation, update and deletion: deleting a stack deletes all its resources, unless a resource's deletion policy says otherwise. CloudFormation itself has no charge for AWS resource types; you pay for the resources it creates.

Template Sections

Only the Resources section is required. The other sections make templates reusable and self-documenting. Each section is described below.

AWSTemplateFormatVersion and Description
The format version (always 2010-09-09) and a text description shown in the console.
Parameters
Values supplied when a stack is created or updated, with a type, default, allowed values, allowed pattern and constraints. NoEcho masks a value in output.
Mappings
Static lookup tables, such as AMI IDs or instance sizes per Region or per environment, read with Fn::FindInMap.
Conditions
Boolean expressions built with Fn::Equals, Fn::And, Fn::Or and Fn::Not. A resource or output with a Condition is created only when the condition is true, and Fn::If chooses property values.
Rules
Validate parameter combinations before any resource is created, for example requiring a larger instance type when the environment is production.
Resources
The resources to create, each with a logical ID, a type such as AWS::S3::Bucket, properties and optional attributes such as DependsOn, DeletionPolicy, UpdatePolicy and CreationPolicy.
Outputs
Values returned after creation, such as an endpoint URL, which can be exported for use by other stacks.
Metadata
Extra information, including AWS::CloudFormation::Init for cfn-init and AWS::CloudFormation::Interface for parameter grouping in the console.
Transform
Macros that process the template before deployment, such as AWS::Serverless-2016-10-31 for AWS SAM, AWS::Include and AWS::LanguageExtensions.

Parameters and Parameter Types

Parameter types improve validation and reuse. Besides String, Number and CommaDelimitedList, CloudFormation supports AWS-specific parameter types, such as AWS::EC2::VPC::Id, AWS::EC2::Subnet::Id and AWS::EC2::KeyPair::KeyName, which the console validates and presents as drop-down lists. Systems Manager parameter types, such as AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>, take the name of a Parameter Store parameter and resolve its value at deployment time. AWS publishes the latest AMI IDs as public parameters, such as /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64, so a template can always use the current AMI without editing. The value is resolved again on each stack update, which can replace instances when a new AMI has been published.

Dynamic references, such as {{resolve:ssm:/orders/prod/instance-type}}, {{resolve:ssm-secure:...}} and {{resolve:secretsmanager:...}}, retrieve values inside resource properties without declaring a parameter, as described in the AWS CodeBuild module for secrets.

Intrinsic Functions and Pseudo Parameters

Intrinsic functions compute values at deployment time. The most important ones are summarised in the table below, after which pseudo parameters are described.

FunctionReturnsExample use
RefA parameter's value or a resource's primary identifierRef: MyBucket returns the bucket name
Fn::GetAttA resource attribute!GetAtt MyQueue.Arn
Fn::SubA string with variables substituted!Sub 'arn:aws:s3:::${MyBucket}/*'
Fn::Join, Fn::Split, Fn::SelectCombined or split strings and list elementsBuilding comma-separated lists
Fn::FindInMapA value from MappingsAMI ID for the current Region
Fn::IfOne of two values based on a conditionLarger instances in production
Fn::ImportValueAn exported output of another stackVPC ID from a network stack
Fn::GetAZs and Fn::CidrAvailability Zones of a Region; CIDR blocksSubnets across AZs
Fn::Base64A Base64-encoded stringEC2 user data

Pseudo parameters are predefined references that need no declaration: AWS::Region, AWS::AccountId, AWS::StackName, AWS::StackId, AWS::Partition, AWS::URLSuffix and AWS::NoValue, which removes a property when returned from Fn::If. Using AWS::Region, AWS::AccountId and AWS::Partition instead of hard-coded values makes a template deployable in any account, Region and partition, which is essential for StackSets.

Dependencies and Ordering

CloudFormation builds a dependency graph and creates independent resources in parallel. A resource that uses Ref or Fn::GetAtt on another resource has an implicit dependency and is created after it and deleted before it. When a dependency exists that the template does not express through references, DependsOn declares it explicitly. A classic example is an EC2 instance in a public subnet that needs internet access during boot: it must depend on the VPC gateway attachment, otherwise the instance could start before the internet gateway is attached. Circular dependencies cause a validation error and are resolved by restructuring, for example by moving a security group rule into a separate AWS::EC2::SecurityGroupIngress resource.

The Stack Lifecycle

A stack moves through statuses that report the progress of each operation. During creation, a stack is CREATE_IN_PROGRESS and ends CREATE_COMPLETE. If any resource fails, the default behaviour is to roll back: CloudFormation deletes the resources it created, and the stack ends in ROLLBACK_COMPLETE, a state from which it can only be deleted. During an update, a failure rolls back to the previous configuration and ends in UPDATE_ROLLBACK_COMPLETE, after which the stack can be updated again. Stack events record each resource's status and the reason for failures, and the first failure event usually shows the root cause, while later events show resources cancelled because of it.

Two further controls apply to every stack operation. Capabilities are acknowledgements that a template may create IAM resources (CAPABILITY_IAM, or CAPABILITY_NAMED_IAM when resources have custom names) or contains macros that expand it (CAPABILITY_AUTO_EXPAND). A service role is an IAM role that CloudFormation assumes to perform the operation, so the user or pipeline only needs permission to call CloudFormation and pass the role, not permission to create every resource; this is a key least-privilege pattern.

500resources

Maximum resources per stack

1MB

Maximum template size when uploaded through S3

51,200bytes

Maximum template body passed directly

The following diagram shows the statuses for create and update operations.

Stack statuses for create and update operations. A create goes from CREATE_IN_PROGRESS to CREATE_COMPLETE; if a resource fails, CloudFormation rolls back by deleting what it created, ending in ROLLBACK_COMPLETE, from which the stack can only be deleted. An update goes from UPDATE_IN_PROGRESS to UPDATE_COMPLETE; a failure rolls back to the previous configuration and ends in UPDATE_ROLLBACK_COMPLETE, after which the stack can be updated again.
The first failure event in the stack events usually shows the root cause.
Scenario questions

Read the stack status

Exam skills 2.1.1 · 5.3.1

Practise what to do in each stack status.

Log in to try this activity Interactive activities are free with an account.
Worked example

A Reusable Template

A team needs the same web tier in development and production. Production must use larger instances, always use the latest Amazon Linux AMI and run in any Region.

AWSTemplateFormatVersion: "2010-09-09"
Parameters:
  Environment:
    Type: String
    AllowedValues: [dev, prod]
  LatestAmiId:
    Type: AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>
    Default: /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64
  SubnetIds:
    Type: List<AWS::EC2::Subnet::Id>
Conditions:
  IsProd: !Equals [!Ref Environment, prod]
Resources:
  LaunchTemplate:
    Type: AWS::EC2::LaunchTemplate
    Properties:
      LaunchTemplateData:
        ImageId: !Ref LatestAmiId
        InstanceType: !If [IsProd, m7g.large, t4g.small]
  WebGroup:
    Type: AWS::AutoScaling::AutoScalingGroup
    Properties:
      MinSize: !If [IsProd, "4", "1"]
      MaxSize: !If [IsProd, "12", "2"]
      VPCZoneIdentifier: !Ref SubnetIds
      LaunchTemplate:
        LaunchTemplateId: !Ref LaunchTemplate
        Version: !GetAtt LaunchTemplate.LatestVersionNumber
Outputs:
  GroupName:
    Value: !Ref WebGroup
    Export:
      Name: !Sub "${AWS::StackName}-WebGroup"

The condition selects sizes, the SSM parameter type resolves the current AMI, the subnet list type validates input, and the export name built with AWS::StackName stays unique per stack. The launch template reference uses LatestVersionNumber so that changes to the template create a new version that the group uses.

Check yourself

A stack creation failed and the stack is in ROLLBACK_COMPLETE. The engineer fixes the template and tries to update the stack. What happens?

Show answer

The update is not allowed. A stack in ROLLBACK_COMPLETE can only be deleted; the engineer must delete it and create it again.

Exam Tips

Remember for the exam

  • Use pseudo parameters (AWS::Region, AWS::AccountId, AWS::Partition) instead of hard-coded values so templates work in any account and Region.
  • SSM parameter types and public AMI parameters keep templates on the latest AMI; dynamic references resolve values and secrets inside properties.
  • Use DependsOn for dependencies not expressed by Ref or GetAtt, such as an instance depending on the gateway attachment.
  • A failed creation ends in ROLLBACK_COMPLETE and must be deleted; a failed update ends in UPDATE_ROLLBACK_COMPLETE and can be updated again.
  • A CloudFormation service role lets users deploy without permissions to create every resource; templates with IAM resources need CAPABILITY_IAM or CAPABILITY_NAMED_IAM.