Home DevOpsTerraform Remote State with S3 Backend: Setup and Best Practices

Terraform Remote State with S3 Backend: Setup and Best Practices

by Knowledge Base Linux
Terraform Remote State with S3 Backend — Terraform Remote State with S3 Backend: Setup and Best Practices

When you run Terraform on your own laptop, the state file lives next to your code and everything feels simple. The moment a second engineer joins — or a CI pipeline runs terraform apply — that local file becomes a liability: state gets out of sync, applies collide, and secrets sit unencrypted on someone’s disk. Configuring Terraform remote state in an Amazon S3 backend solves all three problems at once, giving your team one authoritative, locked, encrypted source of truth for infrastructure state. This guide walks you through the complete setup, from creating a versioned and encrypted bucket, to enabling DynamoDB state locking, to the team best practices that keep production applies safe.

Prerequisites – Terraform Remote State with S3 Backend

Before you start, make sure you have the following ready:

  • Terraform 1.5 or later installed on your workstation (check with terraform version).
  • An AWS account with permissions to create S3 buckets and DynamoDB tables. If you are still learning the basics, read our Terraform for beginners: providers, state, and modules guide first — it explains how state files work and why they matter.
  • The AWS CLI installed and configured with credentials (aws configure), or an IAM role attached to your build runner.
  • A fresh working directory for your Terraform project; do not point a remote backend at a directory that already holds a production terraform.tfstate until you understand state migration in Step 5.

Step 1: Create a Dedicated S3 Bucket for Terraform Remote State – Terraform Remote State with S3 Backend

Never store Terraform remote state in the same bucket as application data. Create a dedicated, tightly-scoped bucket in a region close to your workloads. The bucket name must be globally unique:

aws s3api create-bucket \
  --bucket mycompany-terraform-state \
  --region eu-west-1 \
  --create-bucket-configuration LocationConstraint=eu-west-1

Pick a region deliberately — Terraform reads and writes state on every plan and apply, so latency and data-residency rules both matter.

Step 2: Enable Versioning and Default Encryption

Versioning is the cheapest insurance you will ever buy for Terraform remote state. If a state file is corrupted or accidentally overwritten, any previous version is one click away in the console or one CLI call away. Server-side encryption with AWS-managed keys (SSE-S3) keeps the contents unreadable at rest:

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

aws s3api put-bucket-encryption \
  --bucket mycompany-terraform-state \
  --server-side-encryption-configuration '{
    "Rules": [{
      "ApplyServerSideEncryptionByDefault": {
        "SSEAlgorithm": "AES256"
      },
      "BucketKeyEnabled": true
    }]
  }'

For stricter compliance requirements you can substitute SSE-KMS with a customer-managed key, but AES256 with S3-managed keys is a solid default for most teams.

Step 3: Block Public Access and Tighten the Bucket Policy

A state file can contain database passwords, tokens, and resource IDs, so the bucket must never be public. Enable the full block-public-access settings:

aws s3api put-public-access-block \
  --bucket mycompany-terraform-state \
  --public-access-block-configuration \
    BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true

Then attach a policy that only allows the Terraform users and CI roles you name explicitly. Keep the principal list as short as possible and require TLS in transit:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "DenyInsecureTransport",
      "Effect": "Deny",
      "Principal": "*",
      "Action": "s3:*",
      "Resource": [
        "arn:aws:s3:::mycompany-terraform-state",
        "arn:aws:s3:::mycompany-terraform-state/*"
      ],
      "Condition": { "Bool": { "aws:SecureTransport": "false" } }
    }
  ]
}

Step 4: Create a DynamoDB Table for State Locking

S3 alone cannot prevent two people from running terraform apply at the same time. The backend’s dynamodb_table option fixes that: Terraform acquires a lock item in DynamoDB before writing state and releases it afterwards. Create a pay-per-request table with a partition key named LockID:

aws dynamodb create-table \
  --table-name terraform-state-locks \
  --attribute-definitions AttributeName=LockID,AttributeType=S \
  --key-schema AttributeName=LockID,KeyType=HASH \
  --billing-mode PAY_PER_REQUEST \
  --region eu-west-1

On-demand billing means you pay almost nothing when nobody is applying, which is the normal state of a Terraform project.

Terraform remote state collaboration: team members applying changes with DynamoDB state locking

Step 5: Configure the Backend Block and Migrate State

Now point your project at the backend. Create or edit backend.tf in your project root:

terraform {
  backend "s3" {
    bucket         = "mycompany-terraform-state"
    key            = "projects/networking/terraform.tfstate"
    region         = "eu-west-1"
    encrypt        = true
    dynamodb_table = "terraform-state-locks"
  }
}

Use one key prefix per environment or project — for example envs/prod/terraform.tfstate and envs/staging/terraform.tfstate — so states never collide. Then run:

terraform init

If a local terraform.tfstate exists, Terraform detects it and asks whether to migrate it into the S3 backend. Answer yes after verifying the local state reflects reality (terraform plan should show no unexpected changes). Keep a copy of the old local file until the first remote-backed plan succeeds.

Step 6: Verify Locking, Versioning, and Encryption

Trust, then verify. Run a plan and confirm the state object appears in the bucket with server-side encryption:

terraform plan -out=tfplan

aws s3api head-object \
  --bucket mycompany-terraform-state \
  --key projects/networking/terraform.tfstate \
  --query '{Version: VersionId, Encrypted: ServerSideEncryption}'

To confirm locking works, start terraform apply in one shell and run terraform plan in another within a few seconds — the second command should report that the state is locked and wait or exit, proving the DynamoDB table is doing its job. Also confirm old versions accumulate under versioning after a couple of applies.

Terraform Remote State Best Practices for Teams

Use Separate State per Environment

One monolithic state file makes every apply risky and slow. Split by environment and, for larger estates, by component (networking, compute, data). Smaller states mean faster plans, smaller blast radius, and fewer lock conflicts.

Never Commit State Files to Git

Even encrypted, the state file belongs in S3 only. Add *.tfstate* and .terraform/ to .gitignore today, and scan your repository history for accidentally committed state files containing secrets. Rotate any credentials that were ever committed — our Ansible Vault secrets encryption guide covers the broader habit of keeping secrets out of version control.

Restrict IAM Access with Least Privilege

Give developers read/write on their environment prefixes only. CI apply jobs get a dedicated role with write access; plan-only jobs get read access. Nobody needs s3:DeleteBucket or dynamodb:DeleteTable — ever.

Enable MFA Delete and Cross-Region Replication for Production

For production state, enable MFA Delete on the bucket so a compromised credential cannot wipe history, and replicate the bucket to a second region. Both are cheap relative to the cost of losing state.

Keep Backend Configuration DRY

Backend blocks cannot use variables, so teams either duplicate the block per environment or generate it with partial backend configuration (terraform init -backend-config=prod.hcl) or a wrapper like Terragrunt. Pick one approach and use it consistently.

Troubleshooting Terraform Remote State Issues

“Error acquiring the state lock”

This usually means a previous apply crashed without releasing the lock. Check the lock info with terraform force-unlock -force <LOCK_ID> only after confirming no other apply is running — force-unlocking an active apply can corrupt state. The lock ID is printed in the error message.

“AccessDenied” When Running Init or Plan

Verify your AWS credentials target the right account and region, and that the IAM identity has s3:GetObject, s3:PutObject, s3:ListBucket, plus DynamoDB GetItem, PutItem, and DeleteItem on the lock table. Credential confusion across multiple AWS profiles is the most common cause.

State Drift After Migration

If the first remote-backed plan proposes changes you did not expect, someone applied with different code against the old local state. Resolve drift before writing new state: run terraform plan, review each proposed change, and use terraform import or terraform refresh to reconcile reality with configuration.

Slow Plans on Large States

A state file growing past tens of megabytes signals it is time to split it. Move components into separate configurations with their own backend keys, and reference shared outputs through terraform_remote_state data sources or, better, through published outputs consumed as module inputs.

Conclusion

Moving to Terraform remote state with the S3 backend is one of the highest-leverage changes a team can make: one encrypted, versioned, locked source of truth replaces fragile local files and eliminates the entire class of “it works on my machine” state problems. Create a dedicated bucket with versioning and encryption, add a DynamoDB lock table, split state per environment, and enforce least-privilege IAM — then verify locking and encryption actually work before your first production apply. For the full backend option reference, see the HashiCorp S3 backend documentation.

You may also like

KbLinux

Typically replies within a day

Hello, Welcome to the site. Please click below button for chatting me through Telegram.