Here are two tips for writing more readable CloudFormation templates.
1) Use dot notation to access attributes
The Fn::GetAtt intrinsic function supports the use of dot notation to refer to a resource’s attribute. It works both the long Fn::GetAtt
and short !GetAtt
forms of the syntax. Instead of the long, enumerated, YAML array syntax:
Value: Fn::GetAtt: - MyResource - Arn
Use the one-liner version:
Value: !GetAtt MyResource.Arn
2) Use !Sub instead of !Join
When creating a string, using !Sub is often a much better option than using !Join. Here’s an example of building an ECR repository URI:
Value: Fn::Join: - '.' - - !Ref 'AWS::AccountID' - dkr - ecr - !Ref 'AWS::Region' - amazonaws.com - '/' - !Ref 'ServiceName'
With this approach, it’s hard to grasp what the string looks like, it’s hard to write correctly and it’s hard to debug. Now compare it to using !Sub:
Value: !Sub '${AWS::AccountId}.dkr.ecr.${AWS::Region}.amazonaws.com/${ServiceName}'
A cool thing to notice is the explicit !Ref on pseudo-parameters and template parameters. This makes the whole construction so much nicer. If you need to access an attribute, you can use the dot notation as mentioned above.
I hope you find these tips useful and apply them in your practice.