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]
References
- Use the Fn::Sub function in AWS CloudFormation | AWS re:Post
- https://github.com/awslabs/aws-cloudformation-templates/blob/master/aws/services/CloudFormation/FindInMap_Inside_Sub.yaml
- amazon web services - How to use !FindInMap in !Sub | userdata section - Stack Overflow
- Fn::FindInMap - AWS CloudFormation
- CloudFormation template Mappings syntax - AWS CloudFormation
- Fn::Sub - AWS CloudFormation