Sub topic 6
Intrinsic functions: Ref, GetAtt, Sub, Join and Select
This chapter assumes you can read a CloudFormation template in YAML and know the main sections (Parameters, Resources, Outputs). It also assumes you have run aws cloudformation deploy at least once. Intrinsic functions are built-in functions that CloudFormation evaluates when it processes a template. They let one part of a template use values from another part, or values that only exist after a resource is created.
What intrinsic functions do
A template is static text. Many values you need are not known until deploy time: the ID of a bucket CloudFormation names for you, the stack's Region, or a parameter chosen by the caller. Intrinsic functions fill those gaps.
In YAML you can write a function in two forms:
- Long form:
Fn::Join(orRef) as a key, with its arguments as the value. - Short form:
!Join,!Ref,!Suband so on, which is the usual choice.
Both forms mean the same thing. You can nest functions, with one exception covered in the gotchas below: the short form cannot be written twice in a row on the same line, such as !Base64 !Sub. Write the inner function in long form or on its own line.
The functions for conditions and lookups appear in later chapters. This chapter covers Ref, Fn::GetAtt, Fn::Sub, Fn::Join and Fn::Select, plus Fn::Split, which pairs with Select.
Ref
Ref returns the value of a parameter, or the default identifier of a resource.
- For a parameter, it returns the parameter's value.
- For a resource, it returns whatever that resource type defines as its return value for
Ref. This differs by type. ForAWS::S3::Bucketit is the bucket name. ForAWS::EC2::Instanceit is the instance ID. ForAWS::SQS::Queueit is the queue URL. ForAWS::IAM::Roleit is the role name, not the ARN.
The "Return values" section of each resource type's documentation states what Ref returns. Check it before you assume.
When a resource uses Ref on another resource, CloudFormation creates the referenced resource first. This is an implicit dependency, covered in a later chapter.
Fn::GetAtt
Fn::GetAtt returns one named attribute of a resource. Use it when Ref does not give you what you need, for example the ARN of a bucket or the DNS name of a load balancer.
Value: !GetAtt AppBucket.ArnThe short form uses a dot between the logical ID and the attribute name. The long form takes a list:
Value:
Fn::GetAtt: [AppBucket, Arn]Available attributes depend on the resource type. A name that the type does not define fails at validation or create time. GetAtt also creates an implicit dependency.
| Need | Function | Example |
|---|---|---|
| Parameter value | `Ref` | `!Ref EnvName` |
| Bucket name | `Ref` | `!Ref AppBucket` |
| Bucket ARN | `Fn::GetAtt` | `!GetAtt AppBucket.Arn` |
| Bucket domain name | `Fn::GetAtt` | `!GetAtt AppBucket.DomainName` |
Fn::Sub
Fn::Sub substitutes variables into a string. Inside the string, ${Name} is replaced by the value of a parameter, a pseudo parameter, or a resource (the same value Ref would give). ${Resource.Attribute} works like GetAtt.
Tags:
- Key: Name
Value: !Sub "${AWS::StackName}-${EnvName}"Sub is usually clearer than Join for building strings, because the result reads like the text it produces. A bucket ARN for objects can be written as !Sub "${AppBucket.Arn}/*".
You can also pass a map of your own variables as a second argument. This is useful for values that are not template names:
UserData:
Fn::Base64:
Fn::Sub:
- |
#!/bin/bash
echo "Environment: ${Env}" > /etc/app-env
- Env: !Ref EnvNameTo write a literal ${ that Sub must not replace, use ${!Literal}. The output is ${Literal}. This matters in shell scripts inside UserData, where ${HOME} would otherwise be treated as a template variable and cause an error.
Fn::Join and Fn::Split
Fn::Join concatenates a list of values with a delimiter. The arguments are the delimiter, then the list.
Resource: !Join
- ""
- - !GetAtt AppBucket.Arn
- "/*"An empty delimiter joins the values with nothing between them. The result is the bucket ARN followed by /*. A comma delimiter produces a comma-separated string:
Value: !Join [",", [!Ref SubnetA, !Ref SubnetB]]Fn::Split does the reverse. It takes a delimiter and a string and returns a list.
Prefer Sub when you are building a single string from named pieces. Use Join when you already have a list, or when the pieces are the results of other functions and a Sub map would be noisier.
Fn::Select
Fn::Select picks one item from a list by zero-based index. The arguments are the index, then the list.
SubnetId: !Select [0, !Ref SubnetIds]Here SubnetIds is a parameter of type List<AWS::EC2::Subnet::Id>, so Ref returns a list. Index 0 is the first item.
A common pattern combines Select with Split or with Fn::GetAZs:
AvailabilityZone: !Select [0, !GetAZs ""]Fn::GetAZs with an empty string returns the Availability Zones of the stack's Region, so this picks the first one. With Split, you can take a piece out of a string:
Value: !Select [1, !Split ["/", !GetAtt AppBucket.Arn]]An index that is out of range makes the operation fail, so check list lengths when the list comes from a parameter.
A working template
This template uses all five functions. Save it as functions.yaml.
AWSTemplateFormatVersion: "2010-09-09"
Description: Intrinsic function demo
Parameters:
EnvName:
Type: String
Default: dev
Names:
Type: CommaDelimitedList
Default: "alpha,beta,gamma"
Resources:
AppBucket:
Type: AWS::S3::Bucket
ReadPolicy:
Type: AWS::IAM::ManagedPolicy
Properties:
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action: s3:GetObject
Resource: !Join ["", [!GetAtt AppBucket.Arn, "/*"]]
Outputs:
BucketName:
Value: !Ref AppBucket
Label:
Value: !Sub "${AWS::StackName}-${EnvName}"
SecondName:
Value: !Select [1, !Ref Names]
ObjectsArn:
Value: !Sub "${AppBucket.Arn}/*"Deploy it and read the outputs:
aws cloudformation deploy \
--template-file functions.yaml \
--stack-name fn-demo \
--capabilities CAPABILITY_IAM
aws cloudformation describe-stacks \
--stack-name fn-demo \
--query "Stacks[0].Outputs"SecondName is beta, because a CommaDelimitedList parameter is a list and index 1 is the second item. Delete the stack with aws cloudformation delete-stack --stack-name fn-demo when you finish.
How evaluation works
Parameters and pseudo parameters resolve first, because they are known at submission. Ref and GetAtt on resources resolve only after the target resource exists. That is why they create the ordering between resources.
Common errors and gotchas
- Wrong
Refassumption. Using!Ref MyRolewhere an ARN is needed passes the role name, and the update fails with a validation error. Use!GetAtt MyRole.Arn. - Unknown attribute.
!GetAtt AppBucket.Namefails because the bucket type has noNameattribute. Look up the valid attributes. - Short forms cannot be chained directly.
!Base64 !Sub "..."is rejected by the YAML parser. UseFn::Base64:on one line and the!SuborFn::Sub:form beneath it. - Unescaped
${}inSub. Shell variables inUserDataneed${!VAR}, or the stack fails with an unresolved variable error. - Circular references. If A uses
GetAtton B and B usesRefon A, CloudFormation reports a circular dependency and refuses the template. Break the cycle by moving one value to a separate resource or by using a plain string. - Unusable in some places. Functions cannot be used in the
Mappingssection keys or inParametersdefaults. Pseudo parameters and resource references are not allowed in aMappingslookup key position outsideFindInMap. - Out-of-range
Select. Selecting index 3 from a three-item list fails the operation.
Exercises
Exercise
A template needs the ARN of an AWS::SQS::Queue named JobQueue in an IAM policy statement. Which expression is correct, !Ref JobQueue or !GetAtt JobQueue.Arn, and why?
Show answer
!GetAtt JobQueue.Arn. Ref on an SQS queue returns the queue URL, not its ARN, and an IAM policy needs the ARN.
Exercise
Rewrite !Join ["-", [!Ref "AWS::StackName", !Ref EnvName, "bucket"]] using Fn::Sub.
Show answer
!Sub "${AWS::StackName}-${EnvName}-bucket"
Exercise
A parameter Subnets is a CommaDelimitedList with the value subnet-a,subnet-b,subnet-c. What does !Select [2, !Ref Subnets] return, and what happens with !Select [3, !Ref Subnets]?
Show answer
Index 2 returns subnet-c, because indexes start at 0. Index 3 is out of range, so the operation fails.