Intrinsic Function Ref
What you'll learn: How to use the Ref intrinsic function to pass values between CloudFormation parameters and resources within your template.
What Is the Ref Function?
In CloudFormation, the Ref function (short for "reference") is your primary tool for connecting different parts of your template together. Think of it like a pointer: instead of hardcoding values, you reference the parameter name or logical resource ID, and CloudFormation automatically fills in the appropriate value at runtime.
When you use Ref with a parameter, it returns the parameter's value. When you use it with a resource's logical ID, it returns that resource's primary identifier (like an instance ID, bucket name, or ARN—depending on the resource type).
Why This Matters
Without Ref, your templates would be static and inflexible. The Ref function enables:
- Reusability: Pass different parameter values for dev, staging, and production
- Resource dependencies: Connect resources by referencing one resource's ID in another's configuration
- Dynamic values: Let CloudFormation determine resource identifiers instead of guessing
Syntax
In YAML:
!Ref LogicalNameOrParameter
In JSON:
{ "Ref": "LogicalNameOrParameter" }
Simple Example
Parameters:
InstanceTypeParam:
Type: String
Default: t2.micro
Resources:
MyEC2Instance:
Type: AWS::EC2::Instance
Properties:
InstanceType: !Ref InstanceTypeParam
Here, !Ref InstanceTypeParam retrieves the parameter value. If you later referenced !Ref MyEC2Instance elsewhere, CloudFormation would return the instance ID.
Key Takeaway: The Ref function connects parameters and resources by returning parameter values or resource identifiers, making your CloudFormation templates dynamic and interconnected.