CloudFormation Templates: Using Ref to Access Run Time Information

When working with AWS CloudFormation, many of the resource properties we reference in our stack template will not be available until the stack is built and creation of that particular resource has been initiated.

For example, suppose we’re declaring an ECS service called MigrateDatabaseService to run and maintain a task based on the MigrateTask task definition. One of the required properties of the AWS::ECS::Service resource is a string containing the Amazon Resource Name (ARN) of the task definition (including the revision number) that we want to run on the cluster. The problem is that the task definition is declared in the same template, but the ARN will not be available until run time. So, how do we specify a run time value at design time?

CloudFormation provides eleven built-in, or intrinsic, functions that we can use to assign values to properties that are not available until run time.

The intrinsic function we need to use to populate the TaskDefinition property in the service resource declaration is the Ref function. Given the logical name of another resource declared in the template, Ref returns the value of the specified resource.

The AWSdocumentation provides an extensive list of the reference values returned by the Ref function for many different resource types, along with example return values. We can see that, for a TaskDefinition resource, Ref returns the task definition ARN, which is exactly what we need to declare the TaskDefinition property in the template:

Note that CloudFormation templates are required to be valid JSON, which means the TaskDefinition property requires a single value. So, while the call to Ref returns a single value, CloudFormation will see the call itself (“Ref”: “MigrateTask”) as another key/value pair, and will generate a template format error (“Expected ‘,’ instead of ‘:’”). Make the call to Ref  by enclosing it in curly brackets so that CloudFormation sees it as a single object, not a key/value pair.

Announcing BBST Scholarships

As we continue to update the BBST course material to help keep the courses relevant and provide a richer learning experience for students and instructors, we also look for additional ways to make the courses available to more people. While we believe that BBST courses...