Using !FindInMap Inside !Sub | CloudFormation

This post summarizes how to use !FindInMap inside !Sub in AWS CloudFormation.

Introduction

CloudFormation's !Sub is a function that substitutes values into a string, while !FindInMap retrieves values from Mappings.
(!Sub is a shorthand for Fn::Sub, and !FindInMap is a shorthand for Fn::FindInMap.)

Here are some typical usage examples:

# Example usage of !Sub:
ExampleArn: !Sub 'arn:aws:ec2:${AWS::Region}:${AWS::AccountId}:instance/instance-id'
# -> ${AWS::Region} and ${AWS::AccountId} are substituted into the string

# Example usage of !FindInMap:
Mappings: 
  RegionMap: 
    us-east-1: 
      "HVM64": "ami-0ff8a91507f77f867"
    us-west-1: 
      "HVM64": "ami-0bdb828fd58c52235"
Resources: 
  myEC2Instance: 
    Type: "AWS::EC2::Instance"
    Properties: 
      ImageId: !FindInMap [ RegionMap, !Ref 'AWS::Region', HVM64 ]
# -> Retrieves the corresponding value from Mappings

Sometimes, you may want to combine these two functions to substitute a value retrieved using !FindInMap into a string using !Sub.

This post explains how to use !FindInMap inside !Sub.

Note: This article was translated from my original post.

Using !FindInMap Inside !Sub

You can use !FindInMap inside !Sub as follows:

Mappings:
  LogGroupMapping:
    Test:
      Name: test_log_group
    Prod:
      Name: prod_log_group

Resources:
  myLogGroup:
    Type: 'AWS::Logs::LogGroup'
    Properties:
      LogGroupName: !Sub 
        - 'cloud_watch_${log_group_name}'
        - log_group_name: !FindInMap [ LogGroupMapping, Test, Name ]
# ${log_group_name} is replaced with the result from !FindInMap

Besides simple string substitution using ${...}, !Sub also supports substituting placeholders in its first element using values from its second element (Reference here).

By defining !FindInMap in the second element of !Sub, you can combine these functions:

LogGroupName: !Sub 
  - 'cloud_watch_${log_group_name}'
  - log_group_name: !FindInMap [ LogGroupMapping, Test, Name ]
# ${log_group_name} is replaced with the result from !FindInMap

Conclusion

This post summarized how to use !FindInMap inside !Sub in CloudFormation.

CloudFormation sometimes requires a more complex syntax compared to other IaC tools like Terraform. However, since it's an integral part of AWS, mastering it is worthwhile.

Let's make good use of it!

[Related Articles]

en.bioerrorlog.work

References