|
|
Terraform Remote State
Author: Venkata Sudhakar
By default Terraform stores its state in a local terraform.tfstate file. This works for solo development but breaks for teams - if two engineers run terraform apply at the same time, they corrupt the state file. Remote state solves this by storing the state file in a shared backend such as GCS or S3, and using state locking to prevent concurrent applies. When one engineer runs apply, the backend locks the state file so no one else can modify it until the apply finishes. A second valuable feature is the terraform_remote_state data source, which lets one Terraform configuration read outputs from another. For example a networking module manages your VPC and outputs the VPC ID. An application module can read that ID from the networking module's remote state without duplicating the networking configuration. This is how large teams split infrastructure into independent modules that still share values. The below example shows configuring a GCS backend, then reading outputs from another module using terraform_remote_state.
It gives the following output on init,
Initializing the backend...
Successfully configured the backend "gcs"!
# State now at: gs://myproject-terraform-state/networking/state/default.tfstate
# Concurrent applies are safe - second apply waits for lock to release
It gives the following output,
terraform plan
data.terraform_remote_state.networking: Reading from GCS...
data.terraform_remote_state.networking: Read complete
+ google_container_cluster.gke
network = "projects/myproject/global/networks/myproject-vpc"
Outputs:
cluster_network = "projects/myproject/global/networks/myproject-vpc"
# VPC ID fetched live from networking state - always current, never stale
Always enable versioning on the GCS bucket storing your state. This lets you recover from accidental corruption by restoring a previous version. Never edit terraform.tfstate manually - use terraform state mv, terraform state rm, or terraform import to modify state safely. If you see "state is locked" errors, check whether a previous apply crashed and left a stale lock, then use terraform force-unlock with the lock ID shown in the error.
|
|