0
0
AwsConceptBeginner · 3 min read

What is Fn::Sub in CloudFormation: Simple Explanation and Usage

Fn::Sub is a CloudFormation function that replaces variables in a string with their actual values during stack creation. It helps you build dynamic strings by inserting resource names, parameters, or other values easily.
⚙️

How It Works

Imagine you want to write a letter but leave some blanks to fill in later, like a name or date. Fn::Sub works similarly by letting you write a string with placeholders. When CloudFormation creates your resources, it fills in those blanks with real values.

For example, you can write a string like "Hello, ${Name}!" and CloudFormation will replace ${Name} with the actual value you provide or a resource's name. This makes your templates flexible and reusable without hardcoding values.

💻

Example

This example shows how Fn::Sub replaces variables in a string to create a bucket ARN dynamically.

yaml
Resources:
  MyBucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: my-example-bucket

  BucketPolicy:
    Type: AWS::S3::BucketPolicy
    Properties:
      Bucket: !Ref MyBucket
      PolicyDocument:
        Statement:
          - Effect: Allow
            Action: s3:GetObject
            Resource: !Sub "arn:aws:s3:::${MyBucket}/*"
Output
The policy's Resource becomes arn:aws:s3:::my-example-bucket/* when deployed.
🎯

When to Use

Use Fn::Sub when you need to create strings that include dynamic values like resource names, IDs, or parameters. It is especially helpful for building ARNs, URLs, or any text that depends on other parts of your template.

For example, if you want to attach a policy to a resource but the resource name changes, Fn::Sub lets you write one template that adapts automatically. This saves time and reduces errors from manual updates.

Key Points

  • Fn::Sub replaces variables in strings with actual values during deployment.
  • Variables are written as ${VariableName} inside the string.
  • You can reference resource names, parameters, or pass a map of custom values.
  • It helps keep templates clean, flexible, and easy to maintain.

Key Takeaways

Fn::Sub dynamically inserts values into strings in CloudFormation templates.
It uses ${VariableName} syntax to mark placeholders for replacement.
Ideal for building ARNs, URLs, or any text needing resource or parameter values.
Helps create reusable and adaptable templates without hardcoding values.