Terraform by Example: State Management
State management is crucial for Terraform. This sample code shows how to use `terraform_remote_state` to read outputs from a separate state file.
Code
data "terraform_remote_state" "network" {
backend = "s3"
config = {
bucket = "my-terraform-state-bucket"
key = "network/terraform.tfstate"
region = "us-east-1"
}
}
resource "aws_instance" "app" {
ami = "ami-12345678"
instance_type = "t2.micro"
# Use subnet ID from the network state
subnet_id = data.terraform_remote_state.network.outputs.public_subnet_id
}Explanation
Terraform uses a state file to map your configuration to real-world resources, track metadata, and improve performance. Proper state management is critical; for team environments, state should always be stored remotely (e.g., in S3) with locking enabled to prevent concurrent modifications and corruption. Storing state in version control is strongly discouraged due to security risks.
The terraform_remote_state data source is a powerful tool for decoupling your infrastructure. It allows one Terraform configuration to read the root-level outputs from another configuration's state file. This enables a layered architecture where, for example, an application layer can consume networking details (like subnet IDs) from a separate networking layer without hardcoding values.
Benefits of remote state include:
- Shared Storage: All team members work from the same state file
- Locking: Prevents write conflicts during concurrent runs
- Security: Encrypts state data at rest and in transit
Code Breakdown
data "terraform_remote_state" connects to an external state file.backend = "s3" specifies the type of the remote backend to read from.config block provides the specific credentials and path to the state file.bucket identifies the S3 bucket where the state is stored.key specifies the path to the state file within the bucket..outputs.public_subnet_id accesses a specific output value from that state.
