Free — no signup required

Connecting Layers: Remote State Data Source

2 min read

Bridging the Gap

If the Networking layer and Application layer have separate state files, how does the Application layer know the Subnet IDs it needs to place servers into? You cannot hardcode them — they change between environments (dev, staging, prod).

The answer is the terraform_remote_state data source. This special data source allows one Terraform configuration to read the output values from another configuration's state file in a read-only manner. No writes, no locks — just a read.

How It Works

The Networking layer declares outputs for the values other layers will need — a VPC ID, a list of public subnet IDs, a list of private subnet IDs. The Application layer then points a terraform_remote_state data source at that layer's backend and reads those outputs directly, using a value like the first private subnet ID when placing an instance, exactly as if it were a local variable.

Trade-offs and Alternatives

terraform_remote_state creates a tight coupling between layers — the Application layer must have read access to the Networking layer's state bucket, and it will fail if the Networking layer hasn't been applied yet or if the output name changes.

An alternative approach is to use a data source to look up resources by tag or name rather than reading remote state — querying for "the VPC tagged with this name" instead of reaching into another layer's state file. This approach is more loosely coupled — the Application layer doesn't need access to the Networking state bucket — but it relies on consistent tagging conventions and makes the dependency less explicit.

Interview Tip

A common interview question is: "How do you share values between separate Terraform state files?" Many candidates answer "hardcode the IDs" or "use variables." The correct answer is terraform_remote_state data source (for tight coupling with explicit outputs) or cloud provider data sources like aws_vpc filtered by tags (for loose coupling). Be ready to explain the trade-off: remote state is explicit and fails fast if the dependency is missing; data sources are more resilient but require disciplined tagging.

Key Point: terraform_remote_state only exposes values that are explicitly declared as output blocks in the source configuration. If a value isn't in an output, it cannot be read by another layer — even if it's in the state file. This is a feature, not a bug: it forces layer owners to think carefully about their public interface and prevents accidental coupling to internal implementation details.

This is one of 18 chapters

Every chapter is free — Kubernetes, Terraform, SRE, distributed systems, and more — with fast daily review built in.

Sign up free