How to manage Terraform remote state?
· Category: DevOps & CI/CD
Short answer
Remote state stores the Terraform state file in a shared location such as S3, GCS, or Terraform Cloud. It supports locking to prevent concurrent modifications.
Steps
- Define a backend block.
- Initialize with
terraform init. - Use locking mechanisms like DynamoDB for S3.
Example
terraform {
backend "s3" {
bucket = "my-state-bucket"
key = "terraform.tfstate"
region = "us-east-1"
encrypt = true
dynamodb_table = "terraform-locks"
}
}
Tips
- Use separate state files per environment.
- Enable encryption at rest.
- Use workspaces or separate directories for isolation.
Common issues
- Backend initialization requires running
terraform init. - Lock table must exist before using DynamoDB locking.
- State conflicts occur if locking is not configured.