Skip to main content

Configuring Terraform Remote State on AWS S3

Set up Terraform remote state in an encrypted, versioned S3 bucket with state locking so teams can run apply safely without overwriting each other.

26 Terms

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.

flowchart TD A([Engineer A
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.

HCL
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 back
resource "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 rest
resource "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 public
resource "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 TLS
data "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
}
Bash
cd bootstrap
terraform init
terraform apply
# Note the bucket name, you need it in the backend block
terraform output -raw state_bucket_name
# razorpay-terraform-state-123456789012
Remember

Backend 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.

HCL
# versions.tf
terraform {
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.

Bash
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 bucket
aws 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 mistake
rm -f terraform.tfstate terraform.tfstate.backup
# A plan should read state from S3 and report no changes
terraform plan
Step 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.

Bash
# Terminal 1
terraform apply
# Do you want to perform these actions?
# Enter a value: <- leave this prompt open
Bash
# Terminal 2
terraform 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 state
aws s3 ls s3://razorpay-terraform-state-123456789012/prod/payments-api/
# terraform.tfstate
# terraform.tfstate.tflock

Answer 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.

HCL
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/*",
]
}
}
Tip

Scope 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, and kms:GenerateDataKey on that key.

Step 6: Reuse One Backend Across Environments

Leave the backend block empty and pass the settings per environment with partial configuration files.

HCL
# versions.tf (backend section)
terraform {
backend "s3" {}
}
HCL
# backend-prod.hcl
bucket = "razorpay-terraform-state-123456789012"
key = "prod/payments-api/terraform.tfstate"
region = "ap-south-1"
encrypt = true
use_lockfile = true
Bash
# Switch environments by pointing init at a different file
terraform init -reconfigure -backend-config=backend-dev.hcl
terraform init -reconfigure -backend-config=backend-staging.hcl
terraform init -reconfigure -backend-config=backend-prod.hcl
Step 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.

Bash
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.tfstate
Step 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.

HCL
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
}
Bash
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 Mistake

Putting 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.

Security

State 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.tfstate is 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

Resources

Explore More in Terraform State and Backend Management

All 3 Topics

Frequently Asked Questions

Is Configuring Terraform Remote State on AWS S3 free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Configuring Terraform Remote State on AWS S3 topic cover?

Set up Terraform remote state in an encrypted, versioned S3 bucket with state locking so teams can run apply safely without overwriting each other.

Found a mistake, an outdated step or a broken link?