Overview and What You Will Learn
Terraform remote state stores the terraform.tfstate file in a shared backend such as an S3 bucket instead of on one engineer's laptop. State locking makes sure only one terraform apply can write to that state at a time. Recent Terraform versions (1.11 and later) lock natively in S3 with use_lockfile = true, and the older DynamoDB table approach is now deprecated, though you will still meet it in existing codebases.
In this lab you will:
- Create a versioned, encrypted, private S3 bucket for state with a bootstrap configuration
- Configure the S3 backend with native locking
- Migrate existing local state into the bucket
- Prove that a second concurrent run is blocked by the lock
- Grant least-privilege IAM access to the state
- Reuse one backend block across dev, staging, and prod with partial configuration
- Restore an older state version, and migrate away from DynamoDB locking
Why This Matters in Production
On a team like Swiggy's, two engineers applying to the same environment from local state files can each hold a different version of reality. The second apply overwrites the first, resources are orphaned, and the state no longer matches the cloud. Remote state with locking makes that failure structurally impossible: the second run waits or fails fast, and versioning on the bucket lets you roll back a bad write.
Core Principles
Remote state moves the single source of truth into one shared, protected location. Every engineer and every CI pipeline reads and writes the same object, and a lock stops two writers from colliding.
runs apply]) -->|Acquires lock| S[(S3 bucket
state + lock file)] B([Engineer B
runs apply]) -.->|Blocked| S C([CI pipeline
runs plan]) -->|Reads state| S S -->|Keeps history| V[Older state versions] classDef person fill:#DBEAFE,color:#1E293B classDef store fill:#F97316,color:#ffffff classDef hist fill:#F1F5F9,color:#1E293B class A,B,C person class S store class V hist
With native locking, Terraform writes a small terraform.tfstate.tflock object next to the state using a conditional write. If that object already exists, the write fails and Terraform reports who holds the lock. The lock is deleted when the run finishes.
State often contains secrets in plaintext, such as database passwords and generated keys. That is why the bucket must be private, encrypted, and tightly scoped.
Detailed Step-by-Step Practical Lab
Step 1: Create the State Bucket with a Bootstrap Configuration
The bucket must exist before any backend can use it, so create it from a separate bootstrap configuration that keeps its own local state. Bucket names are global, so the account ID is part of the name.
terraform { required_version = ">= 1.11.0" required_providers { aws = { source = "hashicorp/aws" version = "~> 6.0" } }} provider "aws" { region = "ap-south-1"} data "aws_caller_identity" "current" {} resource "aws_s3_bucket" "terraform_state" { bucket = "razorpay-terraform-state-${data.aws_caller_identity.current.account_id}" lifecycle { prevent_destroy = true # a destroy of this bucket would orphan every stack } tags = { Purpose = "terraform-remote-state" ManagedBy = "terraform-bootstrap" }} # Keep every previous version so a bad write can be rolled backresource "aws_s3_bucket_versioning" "terraform_state" { bucket = aws_s3_bucket.terraform_state.id versioning_configuration { status = "Enabled" }} # State holds secrets in plaintext, so encrypt at restresource "aws_s3_bucket_server_side_encryption_configuration" "terraform_state" { bucket = aws_s3_bucket.terraform_state.id rule { apply_server_side_encryption_by_default { sse_algorithm = "aws:kms" } bucket_key_enabled = true # fewer KMS calls, lower cost }} # State must never be publicresource "aws_s3_bucket_public_access_block" "terraform_state" { bucket = aws_s3_bucket.terraform_state.id block_public_acls = true block_public_policy = true ignore_public_acls = true restrict_public_buckets = true} # Refuse any request that is not sent over TLSdata "aws_iam_policy_document" "deny_insecure_transport" { statement { sid = "DenyInsecureTransport" effect = "Deny" actions = ["s3:*"] resources = [ aws_s3_bucket.terraform_state.arn, "${aws_s3_bucket.terraform_state.arn}/*", ] principals { type = "*" identifiers = ["*"] } condition { test = "Bool" variable = "aws:SecureTransport" values = ["false"] } }} resource "aws_s3_bucket_policy" "terraform_state" { bucket = aws_s3_bucket.terraform_state.id policy = data.aws_iam_policy_document.deny_insecure_transport.json depends_on = [aws_s3_bucket_public_access_block.terraform_state]} output "state_bucket_name" { value = aws_s3_bucket.terraform_state.id}cd bootstrapterraform initterraform apply # Note the bucket name, you need it in the backend blockterraform output -raw state_bucket_name# razorpay-terraform-state-123456789012RememberBackend blocks cannot reference variables, locals, or resources. The bucket name has to be pasted in as a literal, or supplied at init time with
-backend-config.
Step 2: Add the S3 Backend with Native Locking
Add the backend to the terraform block of the stack you want to protect. Use a key hierarchy of environment/service/terraform.tfstate.
# versions.tfterraform { required_version = ">= 1.11.0" required_providers { aws = { source = "hashicorp/aws" version = "~> 6.0" } } backend "s3" { bucket = "razorpay-terraform-state-123456789012" key = "prod/payments-api/terraform.tfstate" region = "ap-south-1" encrypt = true # encrypt the state object with server-side encryption use_lockfile = true # native S3 locking, no DynamoDB table needed }}Step 3: Migrate Existing Local State to S3
Run terraform init -migrate-state. Terraform detects the backend change and offers to copy the existing state to the bucket.
terraform init -migrate-state# Terraform detected that the backend type changed from "local" to "s3".# Do you want to copy existing state to the new backend?# Enter a value: yes## Successfully configured the backend "s3"! # Confirm the object is in the bucketaws s3 ls s3://razorpay-terraform-state-123456789012/prod/payments-api/# 2026-10-13 09:15:32 4521 terraform.tfstate # Remove the stale local copies so nobody uses them by mistakerm -f terraform.tfstate terraform.tfstate.backup # A plan should read state from S3 and report no changesterraform planStep 4: Prove the Lock Blocks a Second Run
Open two terminals in the same directory. In the first, start an apply and leave it waiting at the confirmation prompt, which holds the lock.
# Terminal 1terraform apply# Do you want to perform these actions?# Enter a value: <- leave this prompt open# Terminal 2terraform plan# Error: Error acquiring the state lock## Lock Info:# ID: 3f1c9a52-8d41-4c0e-9b7a-6f2d1e5a7c10# Path: razorpay-terraform-state-123456789012/prod/payments-api/terraform.tfstate# Operation: OperationTypeApply# Who: rahul@mumbai-laptop# Created: 2026-10-13 09:21:07 UTC # While the lock is held, the lock object sits next to the stateaws s3 ls s3://razorpay-terraform-state-123456789012/prod/payments-api/# terraform.tfstate# terraform.tfstate.tflockAnswer no in terminal 1 and the lock object disappears. In CI, use -lock-timeout=5m so a queued run waits for the lock instead of failing at once.
Step 5: Grant Least-Privilege Access to the State
The identity that runs Terraform needs to list the bucket and read, write, and delete objects under its own key prefix. Delete access is required because the lock object is removed when a run ends.
data "aws_iam_policy_document" "terraform_state_access" { statement { sid = "ListStateBucket" actions = ["s3:ListBucket"] resources = ["arn:aws:s3:::razorpay-terraform-state-123456789012"] } statement { sid = "ReadWriteStateAndLock" actions = ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"] resources = [ "arn:aws:s3:::razorpay-terraform-state-123456789012/prod/payments-api/*", ] }}TipScope the object resource to one service prefix so the dev pipeline role can never read prod state. If you encrypt with a customer-managed KMS key, also grant
kms:Encrypt,kms:Decrypt, andkms:GenerateDataKeyon that key.
Step 6: Reuse One Backend Across Environments
Leave the backend block empty and pass the settings per environment with partial configuration files.
# versions.tf (backend section)terraform { backend "s3" {}}# backend-prod.hclbucket = "razorpay-terraform-state-123456789012"key = "prod/payments-api/terraform.tfstate"region = "ap-south-1"encrypt = trueuse_lockfile = true# Switch environments by pointing init at a different fileterraform init -reconfigure -backend-config=backend-dev.hclterraform init -reconfigure -backend-config=backend-staging.hclterraform init -reconfigure -backend-config=backend-prod.hclStep 7: Restore a Previous State Version
Versioning is only useful if you have practised the restore. List the versions, download a good one, then push it back.
aws s3api list-object-versions \ --bucket razorpay-terraform-state-123456789012 \ --prefix prod/payments-api/terraform.tfstate \ --query 'Versions[].[VersionId,LastModified,Size]' \ --output table aws s3api get-object \ --bucket razorpay-terraform-state-123456789012 \ --key prod/payments-api/terraform.tfstate \ --version-id "EXAMPLEVersionId1234" \ restored.tfstate # A restored file has an older serial, so Terraform may demand -force.# Use it only after confirming nobody else is running an apply.terraform state push restored.tfstateStep 8: Migrate Away from DynamoDB Locking
Older stacks lock with a DynamoDB table through the dynamodb_table argument. That argument is deprecated. Move over in two safe changes: enable both lock mechanisms first, then drop the table.
backend "s3" { bucket = "razorpay-terraform-state-123456789012" key = "prod/payments-api/terraform.tfstate" region = "ap-south-1" encrypt = true use_lockfile = true # new native lock dynamodb_table = "terraform-state-lock" # old lock, remove after one release cycle}terraform init -reconfigure# After every team and pipeline is on the new config, delete the# dynamodb_table line, run init -reconfigure again, then delete the table.Production Best Practices & Common Pitfalls
Common MistakePutting the state bucket inside the same Terraform configuration that uses it as a backend. A destroy or a bad edit then removes the bucket holding its own state. Keep the bucket in a separate bootstrap configuration with
prevent_destroy = true.
SecurityState is a full inventory of your infrastructure and often includes secrets in plaintext. Keep the bucket private, encrypted, TLS-only, and readable only by the apply roles and a small set of administrators.
- Store state in a dedicated tooling account. A compromised dev account then cannot read or tamper with prod state. Grant access across accounts with an assumed role.
- Use a consistent key hierarchy.
environment/service/terraform.tfstateis easy to find, audit, and restrict by IAM prefix. - Turn on S3 access logging or CloudTrail data events. Every read and write of state is an infrastructure event worth auditing during an incident.
- Add a lifecycle rule for old versions. Expire noncurrent versions after a set number of days so the bucket does not grow without limit, while still keeping a useful history.
- Pin the Terraform version across the team. A newer CLI can upgrade the state format, and older CLIs then refuse to read it.
- Practise recovery in dev first. Restoring a state version for the first time during a production incident is the wrong time to learn the steps.
Quick Reference & Troubleshooting Commands
| Command | Description |
|---|---|
terraform init -migrate-state |
Copy state from the old backend to the new one |
terraform init -reconfigure |
Switch backend settings without migrating state |
terraform init -backend-config=file.hcl |
Supply partial backend settings at init time |
terraform state pull |
Print the current remote state |
terraform state push file |
Upload a state file to the backend |
terraform plan -lock-timeout=5m |
Wait up to 5 minutes for a held lock |
terraform force-unlock LOCK_ID |
Remove a stuck lock after confirming no run is active |
| Error | Fix |
|---|---|
NoSuchBucket |
Create the bucket first, then run terraform init |
AccessDenied on S3 |
Grant s3:ListBucket on the bucket and Get/Put/Delete on the key prefix |
Error acquiring the state lock |
Wait for the other run, or use force-unlock if it crashed |
Backend configuration changed |
Run terraform init -reconfigure or -migrate-state |
Variables may not be used here |
Use literals or -backend-config in the backend block |
Failed to get existing workspaces |
Check the region and the IAM permissions on the bucket |