Secure Terraform Remote State: A Team Guide
It’s 5:40 p.m. on a Friday. Ana runs a terraform apply to scale up an auto-scaling group. Two minutes later, Luis, working on a different branch, runs his to change a load balancer rule. Both started from a local copy of the state. One overwrites the other, Terraform “forgets” resources that actually exist, and on Monday someone finds a duplicated environment—or worse, a destroyed database.
That’s not bad luck. It’s what happens when several engineers share infrastructure and the file that describes reality—the state—lives on a laptop. In this guide you’ll learn how to set up Terraform remote state with locking, encryption and least-privilege permissions, and how to organize your workflow so that breaking the cloud between two people is hard by design.
What Terraform state is and why it’s so fragile
Terraform doesn’t query the cloud every time to know what it manages. It keeps a map between your code and the real resources in a file, terraform.tfstate. That’s what it uses to calculate the plan: what to create, modify or destroy.
That file has three properties that explain every team problem:
- It’s the operational source of truth. If it’s lost or corrupted, Terraform doesn’t know which resources belong to it and may try to recreate them or leave them orphaned.
- It’s mutable and concurrent. Every
applyrewrites it. Two simultaneous writes without coordination produce an inconsistent state. - It contains sensitive data. Generated database passwords, private keys, tokens and connection strings can end up in plain text inside the JSON, even if you mark the variables as
sensitive.
That’s why local state—or worse, a terraform.tfstate committed to Git—stops being acceptable as soon as more than one person or a pipeline touches the infrastructure.
The three requirements of a serious state backend
Before choosing technology, define what you need. A production remote backend should offer:
- Centralized, versioned storage, so you can recover previous states.
- Locking, so only one operation writes at a time.
- Encryption and access control, both at rest and in transit, with least-privilege permissions.
The most common backends cover all three: S3 on AWS, Google Cloud Storage, Azure Blob Storage, or managed platforms like HCP Terraform from HashiCorp. We’ll use S3 as the example because it’s the most widespread, but the principles carry over to any provider.
Setting up the S3 remote backend step by step
Create the bucket with the right protections
The state bucket is critical infrastructure. Create it separately, once, in an admin or platform account, with these measures:
- Versioning enabled, so you can return to a previous version if an
applygoes wrong. - Encryption at rest with SSE-KMS and a dedicated key, which lets you audit and restrict its use.
- Full public access block.
- A policy that requires TLS and denies any unencrypted request.
- Lifecycle rules that keep old versions for a reasonable time without growing without limit.
You can check the encryption and versioning options in the AWS documentation.
Declare the backend in code
terraform {
required_version = ">= 1.10"
backend "s3" {
bucket = "acme-tfstate-prod"
key = "plataforma/red/terraform.tfstate"
region = "eu-west-1"
encrypt = true
kms_key_id = "alias/tfstate"
use_lockfile = true
}
}
Once you add it, terraform init -migrate-state moves the local state to the bucket. Do the migration once, with the rest of the team notified and no apply in progress.
Enable state locking
Locking is what really prevents the Friday disaster. When Ana runs apply, Terraform acquires a lock. If Luis runs his in the meantime, he gets an error telling him who holds the lock and since when, instead of stepping on anything.
Historically, the S3 backend used a DynamoDB table for this. Since Terraform 1.10, the backend supports native locking in S3 via use_lockfile = true, with no extra tables, and the DynamoDB option is listed as deprecated. If you’re on an older version, keep using dynamodb_table and plan the upgrade.
Never use -lock=false as a shortcut. If a lock bothers you, something’s going on and you want to know about it.
One state per environment and per component
A single giant state is another way to break the cloud: every change competes for the same lock, plans take minutes and one mistake affects everything. Split the state by blast radius:
- By environment: development, staging and production never share state, and ideally not even an account.
- By layer: networking, data, compute and applications change at different rates and should have separate states.
- By team: each team owns its states and who can write to them.
The object key in the bucket mirrors that hierarchy: prod/red/terraform.tfstate, prod/datos/terraform.tfstate. To share data between layers, use terraform_remote_state sparingly or, better, data sources that query the cloud directly so you don’t couple states.
Avoid workspaces as the only mechanism for separating environments: they share a backend and permissions, so they don’t isolate anything important.
State security: permissions, secrets and auditing
Least-privilege with roles
Nobody should have permanent credentials with write access to the production bucket. Apply the principle of least privilege:
- A read role for those running
planand reviewing. - A write role assumable only from the CI/CD pipeline.
- Temporary, federated credentials—never static access keys on laptops.
Enable access logging on the bucket and the KMS key. If the state contains secrets, whoever can read it will have them, so who reads is as important as who writes.
Keep secrets out of the state
Even if you encrypt the backend, the state should ideally contain as few secrets as possible. Generate credentials outside Terraform, read them at runtime from a secrets manager and avoid passing them as literal values. If you’re looking for an open alternative for this, check out our guide on secret management with OpenBao and saying goodbye to .env files in Git. And if you’re coming from Vault, migrating Vault to OpenBao in production walks through the process.
Also add *.tfstate, *.tfstate.backup and .terraform/ to .gitignore from day one.
A workflow where the pipeline is the only one that applies
Remote state with locking prevents collisions, but it doesn’t prevent hasty decisions. The next level of maturity is taking apply off laptops:
- The engineer opens a pull request with the change.
- The pipeline runs
terraform fmt,validateandplan, and posts the plan as a comment. - A teammate reviews the plan, not just the code. That’s where the unexpected
destroyshows up. - On merge, the pipeline runs
applywith the approved plan (terraform apply plan.tfplan).
This model mirrors the logic of GitOps in production with ArgoCD and Kubernetes: Git is the entry point, changes are reviewable and rollbacks are a revert. Add branch protections, mandatory approvals for production states and a per-state run queue so pipelines don’t compete with each other either.
If access to machines and consoles is still a weak spot, complement this with audited access and no permanent keys, like the one described in Teleport: goodbye to SSH keys.
When things go wrong: recovery and state operations
Even with everything set up well, incidents will happen. Know the procedure before you need it.
Orphaned lock. If a pipeline crashes mid-run, the lock may stay held. First confirm there’s no live run, then use terraform force-unlock <ID>. Doing it with an active operation is exactly what the lock was supposed to prevent.
Corrupted state or wrong change. Thanks to bucket versioning, restore the previous version of the object, run terraform plan to confirm it matches reality, and only then continue.
Refactoring without destroying. If you rename a resource or move it to another module, use moved or terraform state mv blocks instead of letting Terraform destroy and recreate. Import existing resources with terraform import or import blocks, always after backing up the state.
Drift. Schedule a periodic terraform plan in read-only mode. If it detects differences, someone changed the cloud by hand and it’s better to find out early.
Common mistakes to avoid
- Storing state in Git “because it’s easier.”
- Sharing a single bucket and write role across all environments.
- Disabling locking “to go faster.”
- Editing the state JSON by hand without a prior backup.
- Forgetting that the state bucket also needs backups, ideally replicated to another region.
- Upgrading Terraform on a laptop: newer versions can update the state format and lock out anyone on an older version. Pin
required_versionand standardize the version in the pipeline.
Conclusion: make the safe path the easy one
A good Terraform remote state doesn’t depend on the team being careful—it depends on the system not allowing the dangerous. An encrypted, versioned backend, locking enabled, small states separated by environment and layer, temporary permissions and a pipeline as the only point of apply turn the Friday at 5:40 p.m. scenario into a harmless error message: “state is locked, wait your turn.”
Start with what removes the most risk: migrate to a remote backend with locking this week. Then separate states, restrict writes and move the apply to the pipeline. Every step reduces the odds that two good engineers accidentally break something that took months to build.