How to Reference Another Cloudformation Stacks Output

Typescript
CDK

Wed May 29 2024

How to Reference Another Cloudformation Stacks Output

Context

It is a good idea to have your Cloudformation Stacks separated as this reduces the area of resources which are impacted per stack deployment, allows for separation of none related resources, and can increase the time that a stack takes to deploy.
However, this can sometimes mean you need to reference another stack within Cloudformation.
An example of this is where you have an ECS Cluster in one stack and consider this your shared Infrastructure then you have 1:n additional stacks for each ECS service. In this instance you will need to reference the Cluster, Load Balancer, and several other resources in your ECS Service stacks.

Exposing the values

In the stack you wish to expose values you will want to define a Cloudformation Output by declaring `CfnOutput` like the following snippet.
new cdk.CfnOutput(this, `ClusterName`, {
value:cluster.clusterName,
exportName:`ClusterName`,
});

 

As you can see the properties that `CfnOutput` is:
  • "value" which is what you want to share to the other stack
  • "exportName" which is a unique name you will use to reference in another stack

Using the values

The using value will be in the stack you wish *import* the value into. In this instance we are making use of cdk's importValue and the value given is a combination of:
  • The stack name where the Output was added to (eg: `stack-a`)
  • The exportName given (eg: `ClusterName`)
const clusterName = cdk.Fn.importValue("stack-aClusterName");

An example

In stack that you are exporting a `CfnOutput` within that is the stack name that you should give it.
If the stack was named `developright-application` and the exportName we set within `CfnOutput` was `BucketName` then we would import this in the additional stack like:
const bucketName = cdk.Fn.importValue("developright-applicationBucketName");

Conclusion

You should now be able to reference output from another stack.