Dependency Management Between Stacks
You'll learn how to safely connect separate Terraform stacks so they can share information and maintain proper ordering without creating a monolithic codebase.
When building complex infrastructure at scale, you often split your Terraform configuration into multiple independent stacks (separate state files). For example, you might have one stack for networking, another for databases, and another for compute resources. But what happens when your compute stack needs to reference a VPC ID from your networking stack?
The Remote State Data Source Pattern
Terraform solves this through remote state data sources. Your networking stack exposes values as outputs, and other stacks read those outputs by referencing the networking stack's state file.
Here's how it works conceptually:
Stack A (Networking) defines outputs:
output "vpc_id" {
value = aws_vpc.main.id
}
Stack B (Compute) reads Stack A's state:
data "terraform_remote_state" "network" {
backend = "s3"
config = {
bucket = "my-terraform-state"
key = "networking/terraform.tfstate"
region = "us-east-1"
}
}
resource "aws_instance" "app" {
vpc_id = data.terraform_remote_state.network.outputs.vpc_id
# ...
}
Managing Dependencies
This pattern creates a dependency chain: Stack B depends on Stack A, so Stack A must be applied first. Think of it like building blocks—you need the foundation (networking) before you can build the walls (compute).
The key benefits: stacks remain independently manageable, teams can own different stacks, and changes to one stack don't force expensive plan operations across everything.
Key Takeaway: Use terraform_remote_state data sources to share outputs between stacks, enabling modular infrastructure while maintaining explicit dependencies through state references.