Remote State
When working in a team, you cannot rely on a local state file. Remote state stores the state centrally, allowing all team members to access and update it. Many backends also support state locking to prevent conflicts.
What Is a Backend?
A backend determines where Terraform stores state. The default backend is
local. Other backends include s3 (AWS), azurerm (Azure), gcs (GCP), and terraform-cloud.Configuring Remote State (AWS S3 Example)
Add a
backend block inside the terraform block:terraform {
backend "s3" {
bucket = "my-terraform-state-bucket"
key = "prod/network/terraform.tfstate"
region = "us-east-1"
encrypt = true
}
}Then run terraform init to migrate the state to S3.State Locking
Many backends support locking (e.g., DynamoDB for S3 backend). Locking prevents two users from running
terraform apply simultaneously, which could corrupt state. For S3, add a dynamodb_table to the backend config.terraform {
backend "s3" {
bucket = "my-terraform-state-bucket"
key = "terraform.tfstate"
region = "us-east-1"
dynamodb_table = "terraform-locks"
encrypt = true
}
}Accessing Remote State Outputs in Another Configuration
You can read outputs from a remote state using the
terraform_remote_state data source:data "terraform_remote_state" "vpc" {
backend = "s3"
config = {
bucket = "my-terraform-state-bucket"
key = "prod/vpc/terraform.tfstate"
region = "us-east-1"
}
}
resource "aws_instance" "web" {
subnet_id = data.terraform_remote_state.vpc.outputs.subnet_id
}Backend Initialization
After changing the backend, you must run
terraform init. It will prompt you to copy existing state to the new backend. For teams, it’s best to set up remote state from the beginning.Two Minute Drill
- Remote state centralizes state for team collaboration.
- Configure backend in
terraformblock, then runterraform init. - State locking (e.g., DynamoDB) prevents concurrent modifications.
- Use
terraform_remote_statedata source to read outputs from other state files.
Need more clarification?
Drop us an email at career@quipoinfotech.com
