How to Configure Remote State Files in Terraform: Step-by-Step Guide

Listen to this Post

Featured Image
Using Infrastructure as Code (IaC) tools like Terraform is a best practice for managing cloud and non-cloud resources. Storing Terraform state files locally works for individual use, but for team projects, a remote backend like Amazon S3 is essential for collaboration and backup.

Why Use a Remote Backend?

  • Shared Access: Multiple team members can access the latest state.
  • Version Control & Backup: Avoid losing state files due to local machine failures.
  • State Locking: Prevent concurrent modifications using DynamoDB.

Step-by-Step Configuration

1. Create an S3 Bucket

aws s3api create-bucket --bucket my-terraform-state-bucket --region us-east-1 

2. Enable Versioning (to track changes and recover older states)

aws s3api put-bucket-versioning --bucket my-terraform-state-bucket --versioning-configuration Status=Enabled 

3. Configure Terraform Backend (`backend.tf`)

terraform { 
backend "s3" { 
bucket = "my-terraform-state-bucket" 
key = "global/s3/terraform.tfstate" 
region = "us-east-1" 
encrypt = true 
dynamodb_table = "terraform-locks" 
} 
} 

4. Set Up DynamoDB for State Locking

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 

5. Initialize Terraform

terraform init 

You Should Know:

  • AWS CLI Setup: Ensure AWS credentials are configured (aws configure).
  • IAM Permissions: The executing user must have:
  • s3:PutObject, s3:GetObject, `s3:ListBucket` for S3.
  • dynamodb:GetItem, dynamodb:PutItem, `dynamodb:DeleteItem` for DynamoDB.
  • Terraform State Commands:
    – `terraform state list` – List resources in the state.
    – `terraform state show ` – Inspect a resource.
    – `terraform state pull` – Download the current state.
  • Force-Unlock State (if manual intervention is needed):
    terraform force-unlock LOCK_ID 
    

What Undercode Say

Using remote state management in Terraform improves security, collaboration, and reliability. S3 + DynamoDB provides a cost-effective way to store and lock state files. Automate this setup in CI/CD pipelines to ensure consistency.

Expected Output:

  • Terraform state stored securely in S3.
  • Concurrent modifications prevented via DynamoDB.
  • Team members can collaborate without state conflicts.

Reference:

How to Configure Remote State Files in Terraform: Step-by-Step Guide

Prediction

As cloud environments grow, Terraform remote backends will become standard, with more teams adopting automated state management and integrating it with DevOps pipelines.

References:

Reported By: Darryl Ruggles – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅

Join Our Cyber World:

💬 Whatsapp | 💬 Telegram