terraform_remote_state is Terraform’s built-in, read-only data source for consuming outputs from another project’s state. It does not modify the referenced state, but it requires backend and configuration settings that identify where that state is stored. section 6.7.1
Reading an RDS output
A service can read an RDS URI from state stored in an S3 backend and pass it into a module: data "terraform_remote_state" "rds" { backend = "s3"; config = { bucket = var.state_bucket_name, key = var.rds_state_path, region = var.state_region } }; module.service receives data.terraform_remote_state.rds.outputs.rds_uri. The producing project must expose rds_uri as a top-level output. section 6.7.1
Use remote state deliberately:
- Set defaults for missing outputs or an empty new state when a hard dependency should become a recoverable, staged dependency. section 6.7.1
- Keep remote-state calls in the top-level module when possible, then pass ordinary values into reusable child modules. section 6.7.2
- Consider provider data sources first; use input variables or remote state when resource lookup is unavailable, imprecise, or impractical. section 6.7.3
- Treat access as a security boundary because readers of state can also read sensitive attributes stored there. section 6.7.3
Listing 6.19 Reading an RDS instance from another state
data "terraform_remote_state" "rds" { #1
backend = "s3" #2
config = { #3
bucket = var.state_bucket_name
key = var.rds_state_path
region = var.state_region
}
}
module "service" {
source = "./modules/service" #4
image = "my_example_image" #5
env = { #6
rds_uri : data.terraform_remote_state.rds.outputs.rds_uri #7
}
}
Inspect the annotated configuration showing backend selection, state location, output access, and module wiring. section 6.7.1
