Fn::ImportValue and Cross-Stack References
What you'll learn: How to share resources between CloudFormation stacks by importing exported values from one stack into another.
Why Cross-Stack References Matter
Imagine you have a VPC created in one CloudFormation stack, but you need to launch EC2 instances in that VPC from a completely different stack. Instead of hardcoding the VPC ID or recreating the VPC, CloudFormation lets you export values from one stack and import them into another. This creates a clean, maintainable link between stacks.
How It Works
In your source stack (the one creating the resource), you use the Outputs section with an Export property to make a value available:
Outputs:
VPCId:
Value: !Ref MyVPC
Export:
Name: SharedVPCId
In your consuming stack, you use Fn::ImportValue (or the !ImportValue shorthand) to retrieve that exported value:
Resources:
MyEC2Instance:
Type: AWS::EC2::Instance
Properties:
SubnetId: !ImportValue SharedVPCId
Key Characteristics
- Export names must be unique within a region in your AWS account
- You cannot delete a stack while another stack is importing its exported values
- Changes to exported values require careful coordination between stacks
- This pattern encourages modular infrastructure design (networking stack, application stack, database stack, etc.)
When to Use It
Cross-stack references work best when you have stable, shared infrastructure (VPCs, security groups, IAM roles) that multiple applications or teams need to reference.
Key Takeaway: Use Fn::ImportValue to import values exported from other CloudFormation stacks, enabling resource sharing and stack modularity without hardcoding values or duplicating infrastructure.