Course contentsShow
← Cloud and Infrastructure
Lesson 865 of 2,98916. AWS CloudFormationFree lesson

Fn::Sub for String Substitution

Build dynamic strings by substituting variables and pseudo parameters with the Sub function.

What You'll Learn

You'll learn how to use the Fn::Sub intrinsic function to build dynamic strings in CloudFormation templates by inserting values from parameters, pseudo parameters, and resource attributes into text.

The Need for String Substitution

When creating AWS resources, you often need to construct strings that include variable values—like combining an environment name with a resource identifier, or embedding parameters in a user data script. Instead of manually concatenating pieces, CloudFormation offers Fn::Sub (short for "substitute") to insert variables directly into template strings.

Think of Fn::Sub like a mail merge: you write a template with placeholders, and CloudFormation fills in the blanks with actual values when the stack is created.

How Fn::Sub Works

The function uses ${VariableName} syntax within a string. CloudFormation replaces these placeholders with the actual values:

YAML syntax:

!Sub 'string with ${Variable}'

JSON syntax:

{"Fn::Sub": "string with ${Variable}"}

You can substitute parameters, pseudo parameters (like AWS::Region), and resource attributes obtained via Fn::GetAtt.

Basic Example

Parameters:
  Environment:
    Type: String
    Default: dev

Resources:
  MyBucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: !Sub 'myapp-${Environment}-${AWS::Region}-bucket'

Here, if Environment is "dev" and the region is "us-east-1", the bucket name becomes myapp-dev-us-east-1-bucket.

When to Use Fn::Sub

Use Fn::Sub whenever you need to build composite strings from multiple values—especially in resource names, tags, configuration scripts, or any text field requiring dynamic content.

Key Takeaway:
Fn::Sub lets you build dynamic strings in CloudFormation by substituting parameters, pseudo parameters, and attributes directly into text using ${Variable} placeholders, making templates flexible and reusable.