Lesson 1 of 4 AWS SAM and CloudFormation

Defining and Updating Stacks with CloudFormation Templates

This lesson explains how AWS CloudFormation creates and updates resources from declarative templates and manages them together as a stack. Most other AWS deployment tools, including AWS SAM and the CDK, are built on it.

Learning outcomes

After completing this lesson, you will be able to:

  • Describe the sections of a CloudFormation template.
  • Explain how intrinsic functions such as !Ref, !GetAtt and !Sub supply values at deployment time.
  • Explain how change sets, deletion policies and stack policies protect resources during updates.

Template sections

A CloudFormation template is a JSON or YAML document that describes a set of resources, and CloudFormation creates, updates and deletes them together as a stack. The template is organised into sections, of which only Resources is required.

Resources declares each resource with a logical ID, a type such as AWS::S3::Bucket and its properties. CloudFormation works out the order of creation from the references between resources. Parameters make one template reusable: values such as an environment name or instance type are supplied when the stack is deployed, and can be restricted with allowed values or AWS-specific types. Mappings are fixed lookup tables inside the template, for example a different instance size for each environment. Conditions evaluate parameters to decide whether a resource or property is created, so one template can produce a small development stack and a full production stack. Outputs return values, such as an API URL, after deployment, and an output can be exported so that other stacks in the same account and Region can import it. The following table summarises the sections.

SectionPurpose
ResourcesThe resources to create (the only required section)
ParametersInput values supplied at deployment time
MappingsLookup tables, such as AMI IDs per Region
ConditionsCreate resources only in some circumstances, such as production
OutputsValues returned by the stack, optionally exported to other stacks

Functions and references

Values in a template often depend on things that are not known until deployment, such as the ARN of a resource created in the same stack. Intrinsic functions supply them.

!Ref returns the value of a parameter or, for a resource, its main identifier, which differs by type: a bucket's name, a queue's URL or a function's name. !GetAtt returns a specific attribute of a resource, such as its ARN or an endpoint address, and is needed whenever !Ref does not return the value required. !Sub builds a string by substituting parameters, resource values and pseudo parameters into placeholders, such as ${Env}. !FindInMap reads a value from a mapping, and !ImportValue reads an output that another stack has exported.

Pseudo parameters, such as AWS::Region and AWS::AccountId, are predefined by CloudFormation, so a template can name resources uniquely without hard-coding the account or Region. Dynamic references fetch a value from Parameter Store or Secrets Manager when the stack is deployed, so a database password is never written in the template or shown in the console. The following table summarises these features.

FeatureWhat it does
!RefReturns a parameter value or a resource's ID
!GetAttReads a resource attribute, such as an ARN
!SubSubstitutes values into a string
!FindInMapReads a value from a mapping
!ImportValueReads an output exported by another stack
Pseudo parametersAWS::Region, AWS::AccountId, AWS::StackName avoid hard-coding environment details
Dynamic references{{resolve:ssm:...}} and {{resolve:secretsmanager:...}} fetch values at deploy time, so secrets never appear in the template

Example. A bucket named after the environment, versioned only in production, retained on stack deletion, with its ARN exported.

AWSTemplateFormatVersion: "2010-09-09"
Parameters:
  Env:
    Type: String
    AllowedValues: [dev, prod]
Conditions:
  IsProd: !Equals [!Ref Env, prod]
Resources:
  ReportsBucket:
    Type: AWS::S3::Bucket
    DeletionPolicy: Retain
    Properties:
      BucketName: !Sub "reports-${Env}-${AWS::AccountId}"
      VersioningConfiguration:
        Status: !If [IsProd, Enabled, Suspended]
Outputs:
  ReportsBucketArn:
    Value: !GetAtt ReportsBucket.Arn
    Export:
      Name: !Sub "${Env}-ReportsBucketArn"

Another stack reads the value with !ImportValue prod-ReportsBucketArn. While it is imported, the exporting stack cannot be deleted and the export cannot change. Nested stacks are the other way to reuse common components.

Updating and protecting stacks

Updates to a CloudFormation stack can replace or remove resources, so several features are provided to preview and protect them. The following list describes these features.

  • Replacement: some property changes update a resource in place; others create a new resource and delete the old one.
  • Change sets preview an update and show Replacement: True where this will happen.
  • Rollback: if creation or an update fails, CloudFormation rolls back by default.
  • Drift detection finds resources changed outside CloudFormation.
  • DeletionPolicy Retain or Snapshot protects data when a stack is deleted, and UpdateReplacePolicy does the same when an update replaces the resource.
  • Stack policies deny updates to critical resources, such as the replacement of a database, and termination protection prevents the whole stack from being deleted.
  • StackSets deploy the same stack across several accounts and Regions.
Worked example

An update that would delete the database

A developer renames a DynamoDB table's key attribute in the template. The change set shows Replacement: True for the table: CloudFormation would create a new table and delete the old one, with all its data.

SafeguardWhat it does
Review change sets before executingShows replacements like this one before they happen
DeletionPolicy: Retain and UpdateReplacePolicy: RetainKeeps the old table if it is ever removed or replaced
Stack policyDenies replacement of the table resource
Termination protectionPrevents the whole stack being deleted

The developer cancels the change set. Changing a key schema genuinely needs a new table and a data migration, which is planned separately rather than done by an accidental stack update.

Check yourself

How can one stack use a value, such as a VPC ID, created by another stack?

Show answer

The first stack exports the value in its Outputs section, and the second reads it with Fn::ImportValue. An exported value cannot be removed while another stack imports it.

Exam Tips

Remember for the exam

  • To reference a resource created in another stack, export the output and use !ImportValue.
  • To preview what an update will change, including replacements, create a change set.
  • To keep a database when its stack is deleted, set DeletionPolicy: Retain or Snapshot.
  • To use a secret in a template without exposing it, use a dynamic reference to Secrets Manager.