patternhclterraformCriticalpending
Terraform state management best practices
Viewed 0 times
terraform stateremote backendlockingstate managementimport
Problem
Need to safely manage Terraform state in a team environment, avoiding state corruption and conflicts.
Solution
Essential state management practices:
State organization:
Safe operations:
Recovery:
# Remote backend with locking
terraform {
backend "s3" {
bucket = "mycompany-terraform-state"
key = "prod/vpc/terraform.tfstate"
region = "us-east-1"
dynamodb_table = "terraform-locks" # State locking
encrypt = true
}
}State organization:
- Split state by blast radius: networking / compute / database
- Use workspaces for environments OR separate state files
- Never store secrets in state (use data sources or vault)
Safe operations:
# Always plan before apply
terraform plan -out=plan.tfplan
terraform apply plan.tfplan
# Import existing resources
terraform import aws_instance.web i-1234567890
# Move resources between states
terraform state mv module.old module.new
# Remove from state without destroying
terraform state rm aws_instance.legacyRecovery:
# Force unlock stuck state
terraform force-unlock LOCK_ID
# Pull and push state manually (emergency)
terraform state pull > backup.tfstate
terraform state push backup.tfstateWhy
Terraform state is the source of truth for infrastructure. Corruption or conflicts can cause resources to be destroyed or orphaned.
Gotchas
- Never edit .tfstate files manually
- State contains sensitive values in plain text
- force-unlock should only be used when you're sure no other operation is running
Context
Team-based infrastructure management with Terraform
Revisions (0)
No revisions yet.