Listen to this Post
When using Terraform, “state files” (with `.tfstate` extension) store the current configuration of resources in JSON format. By default, these files are stored locally, but a better approach is remote storage like AWS S3 for improved collaboration and security.
Remote backends enable teams to manage infrastructure as code (IaC) efficiently. Storing state files in S3 ensures:
– Centralized state management
– Versioning and backup
– Locking mechanisms (via DynamoDB) to prevent conflicts
Read more: Understanding Terraform Remote Backends
You Should Know:
1. Configuring S3 Backend in Terraform
Add this to your `backend.tf`:
[hcl]
terraform {
backend “s3” {
bucket = “your-terraform-state-bucket”
key = “global/s3/terraform.tfstate”
region = “us-east-1”
dynamodb_table = “terraform-locks”
encrypt = true
}
}
[/hcl]
2. Commands to Initialize & Apply
terraform init Initializes backend terraform plan Shows changes terraform apply Applies configuration
3. Enable State Locking with DynamoDB
Create a DynamoDB table:
aws dynamodb create-table \ --table-name terraform-locks \ --attribute-definitions AttributeName=LockID,AttributeType=S \ --key-schema AttributeName=LockID,KeyType=HASH \ --billing-mode PAY_PER_REQUEST
4. Force-Unlock a Stale State (If Needed)
terraform force-unlock LOCK_ID
5. Migrate Local State to S3
First, configure the backend, then run:
terraform init -migrate-state
6. Check State File Contents
terraform state list Lists resources terraform show Displays full state
7. Securely Handle Sensitive Data
Use `terraform.tfvars` with encryption:
Example: AWS credentials aws_access_key = "encrypted_key" aws_secret_key = "encrypted_secret"
What Undercode Say:
Managing Terraform state remotely is critical for team collaboration and security. S3 + DynamoDB provides a robust backend solution with versioning and locking. Always:
– Encrypt state files (encrypt = true)
– Restrict S3 bucket access (IAM policies)
– Automate state backups (S3 versioning)
– Use `terraform state` commands for debugging
For advanced users, consider Terraform Cloud or Terragrunt for large-scale deployments.
Expected Output:
A secure, versioned, and locked Terraform state stored in S3, accessible to authorized team members with proper IAM policies.
Read more: Terraform S3 Backend Docs
References:
Reported By: Darryl Ruggles – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅



