You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
CloudFormation intrinsic functions let you add logic and dynamic behaviour to your templates. Instead of hard-coding values, you can reference other resources, perform string manipulation, look up values from mappings, and conditionally include or exclude resources. Mastering intrinsic functions is what takes you from writing basic templates to writing production-grade infrastructure definitions.
Intrinsic functions are built-in functions that CloudFormation evaluates at deploy time. They are used inside the Properties section of resources, in Outputs, and in Conditions. You cannot use them in the Parameters or Mappings sections (with one exception: Fn::Ref can be used indirectly in Mappings via the !FindInMap function).
In YAML templates, intrinsic functions use the short form with an exclamation mark prefix:
| Full Form | Short Form |
|---|---|
Fn::Ref | !Ref |
Fn::Sub | !Sub |
Fn::GetAtt | !GetAtt |
Fn::Join | !Join |
Fn::Select | !Select |
Fn::Split | !Split |
Fn::FindInMap | !FindInMap |
Fn::GetAZs | !GetAZs |
Fn::ImportValue | !ImportValue |
Fn::If | !If |
Fn::Base64 | !Base64 |
Fn::Cidr | !Cidr |
!Ref returns the value of a parameter or the physical ID of a resource:
# Reference a parameter
InstanceType: !Ref InstanceTypeParam
# Reference a resource (returns its physical ID)
SubnetId: !Ref PublicSubnet
What !Ref returns depends on the resource type. For an AWS::EC2::VPC, it returns the VPC ID. For an AWS::S3::Bucket, it returns the bucket name.
While !Ref returns the primary identifier, !GetAtt retrieves any attribute of a resource:
# Get the public IP of an EC2 instance
Value: !GetAtt WebServer.PublicIp
# Get the ARN of a Lambda function
Value: !GetAtt MyFunction.Arn
# Get the endpoint of an RDS instance
Value: !GetAtt Database.Endpoint.Address
Each resource type has its own set of return attributes documented in the AWS CloudFormation User Guide.
!Sub replaces variables in a string with their values. Variables are enclosed in ${}:
# Simple substitution using a parameter
BucketName: !Sub 'app-${Environment}-assets'
# Using pseudo parameters
BucketName: !Sub '${AWS::StackName}-${AWS::Region}-assets'
# Using a resource reference
Value: !Sub 'https://${ALB.DNSName}/api'
!Sub is one of the most frequently used functions. It is more readable than !Join for most string construction tasks.
!Join concatenates a list of strings with a specified delimiter:
# Join with a hyphen
Value: !Join
- '-'
- - !Ref AWS::StackName
- web
- server
# Result: "my-stack-web-server"
While !Join is still useful, !Sub is preferred for readability in most cases.
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.