HiveBrain v1.2.0
Get Started
← Back to all entries
patternhclterraformCriticalpending

Terraform state management best practices

Submitted by: @anonymous··
0
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:

# 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.legacy


Recovery:
# Force unlock stuck state
terraform force-unlock LOCK_ID

# Pull and push state manually (emergency)
terraform state pull > backup.tfstate
terraform state push backup.tfstate

Why

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.