categories.infrastructure-as-code Intermediate
What is Terraform State? How do you manage remote state for team collaboration?
What Terraform State Does
The state file (terraform.tfstate) records the known state of resources. Terraform uses it to determine the diff between "current state" and "desired state."
Without state: Terraform doesn't know which resources already exist and might recreate or overwrite resources on every apply.
Problems with Local State
- Multiple people running apply simultaneously causes conflicts (race conditions)
- State files contain sensitive data (passwords, keys) and cannot be committed to Git
- Doesn't support team collaboration
Remote State (Remote Backend)
Store state in a shared remote location. Common options:
| Backend | Characteristics |
|---|---|
| AWS S3 + DynamoDB | S3 stores state, DynamoDB provides state locking |
| Terraform Cloud | Official managed service with UI and collaboration features |
| GCS (Google Cloud Storage) | Native choice for GCP environments |
State Locking
Prevents multiple users from modifying state simultaneously. DynamoDB locking configuration:
terraform { backend "s3" { bucket = "my-tf-state" key = "prod/terraform.tfstate" region = "us-east-1" dynamodb_table = "terraform-locks" encrypt = true } }
Best Practices
- State isolation: Use separate state files for each environment (dev/staging/prod)
- Sensitive data: Enable S3 encryption and restrict bucket access
- Never manually edit state: Use terraform state commands instead
✦ AI Mock Interview
Type your answer and get instant AI feedback
Sign in to use AI scoring
