How can I reference a resource in another AWS CloudFormation stack during template creation?

As your AWS CloudFormation usage increases, you can create static stacks to host infrastructure resources. Then, you can create another consumer stack that references the resources as needed, instead of managing stacks individually.

The resource stack serves as a static service that is independent of your application. The reference point works like an interface to allow interaction with consumers. Cross-stack references use an architectural design similar to a service-oriented architecture.

To create a cross-stack reference, use the export output field to flag the value of a resource output for export, and then use the Fn::ImportValue intrinsic function to import the value. Exported values are identified by the names specified in the template, which must be unique to your region.

Note: This article provides one example on how to create a cross-stack reference. For a complete set of instructions, see Walkthrough: Refer to Resource Outputs in Another AWS CloudFormation Stack.

Create an instance using an imported subnet and security group

1.    Open the AWS CloudFormation console, choose Create Stack, and then choose Design template.

2.    At the bottom of the page, choose the Template tab.

3.    Copy a sample template, such as Fn::ImportValue, or use the following example:

"Resources" : {
  "WebServerInstance" : {
    "Type" : "AWS::EC2::Instance",
    "Properties" : {
      "InstanceType" : "t2.micro",
      "ImageId" : "ami-a1b23456",
      "NetworkInterfaces" : [{
        "GroupSet" : [{"Fn::ImportValue" : {"Fn::Sub" : "${NetworkStackNameParameter}-SecurityGroupID"}}],
        "AssociatePublicIpAddress" : "true",
        "DeviceIndex" : "0",
        "DeleteOnTermination" : "true",
        "SubnetId" : {"Fn::ImportValue" : {"Fn::Sub" : "${NetworkStackNameParameter}-SubnetID"}}

Note: Update the template to reflect the names of your resources.

4.    Choose the Create stack icon, choose Next, and type a name.

5.    For Parameters, enter the network stack name that you want to cross-reference.

6.    Choose Next, and then choose Next again.

7.    From the CloudFormation drop-down menu, choose Exports to view the export names and values.

8.    Open the Amazon EC2 console.

9.    In the navigation pane, under Instances, choose the Instance ID that you created.

10.  Choose the Description view, and verify that the security group and subnet have been configured.

Note: The source stack cannot be deleted while its exported values are being used in other stacks. The Export Name must be unique for the account per region.

Did this page help you? Yes | No

Back to the AWS Support Knowledge Center

Need help? Visit the AWS Support Center

Published: 2018-01-09