Terraform state is easy solo and risky across five teams. Learn remote backends, S3 native locking, state splitting and drift detection at scale.
Terraform state works perfectly when one engineer runs it on one laptop. It starts hurting the moment a second engineer applies at the same time. By the time five teams share a few hundred resources across several environments, state is the most dangerous file in your infrastructure workflow.
This post covers what goes wrong and how to design a state setup that survives real multi-team use: remote backends, locking, recovery, state splitting and drift detection.
Terraform state maps each resource in your code to a real object in the cloud, along with IDs, attributes and dependencies. If it is lost, stale or corrupted, Terraform cannot tell what already exists, and it may try to recreate or destroy real infrastructure.
Local state fails in predictable ways. Two engineers apply at once and overwrite each other. The only copy of production state lives on one laptop. Nobody can say who changed what and when.
Three controls fix this, and you need all three before team-scale use:
Also remember that state can contain secrets in plain text, such as database passwords and keys. Treat the state bucket like a secrets store: encrypt it, block public access and restrict who can read it.
Use an S3 bucket with versioning and encryption, and enable native S3 locking with use_lockfile = true. This replaces the older DynamoDB lock table and needs Terraform 1.10 or later, with 1.11 or later recommended.
terraform { required_version = ">= 1.11.0" backend "s3" { bucket = "example-platform-tf-state" key = "prod/payment-service/terraform.tfstate" region = "ap-south-1" encrypt = true kms_key_id = "arn:aws:kms:ap-south-1:111122223333:key/abc-123" use_lockfile = true }}Native locking works by writing a small .tflock object next to the state file, using S3 conditional writes. That means the identity running Terraform needs permission to create and delete that object, not just to read and write the state.
Turn on versioning for the bucket. This is not optional, because it is your undo button:
aws s3api put-bucket-versioning \ --bucket example-platform-tf-state \ --versioning-configuration Status=EnabledIf you are on an older Terraform version, the legacy approach uses a DynamoDB table:
aws dynamodb create-table \ --table-name terraform-state-lock \ --attribute-definitions AttributeName=LockID,AttributeType=S \ --key-schema AttributeName=LockID,KeyType=HASH \ --billing-mode PAY_PER_REQUEST \ --region ap-south-1Then add dynamodb_table = "terraform-state-lock" to the backend block. Plan a migration to native locking, since the DynamoDB option is deprecated.
Here is what locking does when two people collide:
The apply role needs list access on the bucket, plus read, write and delete on its own state prefix. Scoping it to one prefix means a pipeline for the payments team cannot touch networking state.
locals { bucket_arn = "arn:aws:s3:::example-platform-tf-state"} data "aws_iam_policy_document" "tf_apply_state" { statement { actions = ["s3:ListBucket"] resources = [local.bucket_arn] } statement { actions = [ "s3:GetObject", "s3:PutObject", "s3:DeleteObject", ] resources = [ "${local.bucket_arn}/prod/payment-service/*", ] }}The DeleteObject permission is what lets Terraform release the .tflock file. Without it, every apply leaves a stuck lock behind. The read-only drift role gets only s3:ListBucket, s3:GetObject and kms:Decrypt.
Restore the previous version of the state object from S3 versioning. Because every write creates a new version, recovery takes minutes if you have the commands ready.
BUCKET=example-platform-tf-stateKEY=prod/payment-service/terraform.tfstate ## list recent versions of the state objectaws s3api list-object-versions \ --bucket "$BUCKET" --prefix "$KEY" --max-items 5 ## copy a known-good version back as the current oneaws s3api copy-object \ --bucket "$BUCKET" --key "$KEY" \ --copy-source "$BUCKET/$KEY?versionId=$VERSION_ID"After restoring, run terraform plan and read it carefully before you apply anything. A restored state that is older than reality will show differences you must understand first.
š” Tip: If you are still on the legacy DynamoDB backend, a restored file can fail with a checksum mismatch, because the table stores a digest of the state. The error message prints the expected value, so update the digest item it names, and then run terraform init again.
Give each independent unit of infrastructure its own state, so a bad apply can only hurt what that state owns. One shared state means any team's mistake can touch every other team's resources.
A common layout uses one key per environment and component:
example-platform-tf-state/ prod/ networking/terraform.tfstate payment-service/terraform.tfstate data-platform/terraform.tfstate staging/ networking/terraform.tfstateChoose boundaries by who owns the resources and how often they change. Too coarse and a failure spreads widely. Too fine and you spend your day coordinating apply order across dozens of states. Orchestration tools such as Terragrunt, Atlantis or the platform features in HCP Terraform help once you pass a handful of states.
Terraform workspaces share one backend configuration, so they are not a substitute for separating production from staging. Use separate keys or buckets, and ideally separate AWS accounts.
Publish only the values other stacks need, and read them through a normal data source. The terraform_remote_state data source works, but it requires read access to the entire state file, including any secrets stored in it.
data "terraform_remote_state" "networking" { backend = "s3" config = { bucket = "example-platform-tf-state" key = "prod/networking/terraform.tfstate" region = "ap-south-1" }} resource "aws_instance" "payment_api" { subnet_id = data.terraform_remote_state.networking.outputs.private_subnet_id}The safer pattern uses SSM Parameter Store as a small, explicit interface between teams. The networking stack publishes a value, and the payments stack reads only that value:
## networking stack: publishresource "aws_ssm_parameter" "private_subnet_id" { name = "/platform/prod/networking/private_subnet_id" type = "String" value = aws_subnet.private.id} ## payment-service stack: readdata "aws_ssm_parameter" "private_subnet_id" { name = "/platform/prod/networking/private_subnet_id"} resource "aws_instance" "payment_api" { subnet_id = data.aws_ssm_parameter.private_subnet_id.value}That way the payments team never needs read access to the networking team's whole state. Keep this interface for non-secret values only, such as IDs, ARNs and names.
A lock error means another run holds the lock, and the message tells you who, when and from where. Check whether that run is still alive before you do anything.
Error: Error acquiring the state lock Lock Info: ID: abc-123-def-456 Path: prod/payment-service/terraform.tfstate Operation: OperationTypeApply Who: ci-runner@build.internal.example.net Version: 1.11.0 Created: 2026-08-20T10:22:31ZIf the owning CI job crashed and is definitely gone, release the lock with its ID:
terraform force-unlock abc-123-def-456Never force-unlock while a real apply may still be running. That is how you get two writers and a corrupted state.
Run a scheduled refresh-only plan per state and alert on exit code 2. Drift means real infrastructure no longer matches state, because someone changed a resource by hand, an autoscaler modified it, or an incident fix was never codified.
name: Drift Detectionon: schedule: ## 02:30 UTC is 08:00 IST, GitHub cron is always UTC - cron: "30 2 * * 1-5" jobs: detect-drift: runs-on: ubuntu-latest permissions: id-token: write contents: read steps: - uses: actions/checkout@v4 - uses: hashicorp/setup-terraform@v3 - uses: aws-actions/configure-aws-credentials@v4 with: role-to-assume: ${{ vars.TF_READONLY_ROLE_ARN }} aws-region: ap-south-1 - run: terraform init -input=false - run: | terraform plan -refresh-only -lock=false \ -detailed-exitcodeExit code 2 means differences were found, so the job fails and your alerting fires. Run it per state, for example with a matrix over your stack directories.
When you find drift, you have three choices:
terraform apply to push reality back to the code.terraform apply -refresh-only to record reality in state, then update code to match.import block, which is reviewable in a pull request.import { to = aws_instance.payment_api id = "i-0abc123def456"}Renames follow the same rule: use a moved block so the change is reviewed, instead of editing state by hand.
moved { from = aws_instance.api to = aws_instance.payment_api}Use HCP Terraform when you would rather not run backend infrastructure, and you want managed remote runs, run history, policy checks and access control in one product. Use S3 when you are AWS-native, already have CI, and want the lowest cost and maximum control.
terraform { cloud { organization = "example-org" workspaces { name = "payment-service-prod" } }}Pricing and free-tier limits for HCP Terraform have changed over time, so check HashiCorp's current plan page before you rely on a free tier. OpenTofu users have their own backend and state encryption options, so check its documentation if you run it.
Backend comparison:
| Backend | Locking | Notes |
|---|---|---|
| Local | None | Never for teams |
| S3 native lock | Yes | Low cost, you run it |
| HCP Terraform | Yes | Managed runs and policy |
Choosing a state boundary:
| Boundary | Blast radius | Coordination |
|---|---|---|
| One state per org | Very large | Low |
| One per team or service | Bounded | Moderate |
| One per resource group | Small | High |
kms:Decrypt and state read access), and reserve write access for the apply role behind OIDC or MFA.required_version and required_providers so a new engineer's laptop cannot silently upgrade state to a newer format.moved and import blocks instead of terraform state mv and terraform import where you can.provider "aws" { default_tags { tags = { ManagedBy = "terraform" Environment = var.environment StatePath = "prod/payment-service" Team = "payments" } }}Noteš References and Further Reading
- Terraform S3 Backend - Locking, encryption and permissions reference
- Terraform Backend Configuration - Official backend docs
- Import Blocks - Reviewable resource imports
- HCP Terraform - Managed runs and state
Both runs read the same state, make changes and write back, so the last writer wins and the other run's records are lost. Terraform can then lose track of real resources and try to recreate them. With locking, the second apply fails immediately with a lock error instead.
Not on current versions. The S3 backend supports native locking with use_lockfile = true, introduced in Terraform 1.10 and stable in 1.11, and the dynamodb_table argument is deprecated. Older Terraform versions still need DynamoDB, so check your version before migrating.
Only after confirming that no apply is still running, for example by checking the CI job that owns the lock ID. Unlocking during a live apply lets a second run write state at the same time, which is a common cause of corruption rather than a fix.
terraform plan takes a state lock by default, and locking needs write access. With a read-only role, run plan with -lock=false and make sure the role can read the state object and decrypt it with the KMS key. Keep write permissions for the apply role only.
A moved block lives in code, goes through pull request review and leaves a git history. terraform state mv edits state directly and is invisible to review. For production renames, prefer moved blocks and keep state mv for emergencies.
Discussion0