Remote State
Store state remotely (for example in an S3 bucket) so a whole team can collaborate safely.
terraform {
backend "s3" { ... }
}By default, state lives in a local terraform.tfstate file. That is fine for solo learning, but a team needs remote state so everyone shares one source of truth.
The S3 backend
A popular choice on AWS stores state in an S3 bucket. Enable versioning on the bucket so you can recover from mistakes.
State locking
Pairing S3 with a DynamoDB table adds locking, which prevents two people from applying at the same time and corrupting state.
Example
terraform {
backend "s3" {
bucket = "soundscode-tf-state"
key = "prod/terraform.tfstate"
region = "us-east-1"
dynamodb_table = "terraform-locks"
encrypt = true
}
}When to use it
- A team stores their Terraform state in an S3 bucket so every engineer and CI pipeline reads and writes the same file instead of maintaining local copies.
- An operator enables versioning on the S3 state bucket so previous state files can be retrieved to roll back after a botched apply.
- A module uses the terraform_remote_state data source to read another stack's outputs, such as reading the VPC ID from the networking team's state.
More examples
S3 backend configuration
Configures S3 as the remote state backend with encryption enabled and a DynamoDB table for state locking.
terraform {
backend "s3" {
bucket = "my-org-terraform-state"
key = "services/api/terraform.tfstate"
region = "us-east-1"
encrypt = true
dynamodb_table = "terraform-state-lock"
}
}Terraform Cloud backend
Uses Terraform Cloud as the backend, which provides state storage, locking, and a run history with no S3 bucket to manage.
terraform {
cloud {
organization = "my-org"
workspaces {
name = "api-production"
}
}
}Read outputs from another stack
Reads the VPC ID output from a separate networking stack's remote state to use in the application stack.
data "terraform_remote_state" "network" {
backend = "s3"
config = {
bucket = "my-org-terraform-state"
key = "network/terraform.tfstate"
region = "us-east-1"
}
}
resource "aws_subnet" "app" {
vpc_id = data.terraform_remote_state.network.outputs.vpc_id
cidr_block = "10.0.20.0/24"
}
Discussion