Introduction
For a small team already using AWS, a practical baseline is a private S3 bucket with versioning, a separate state key for each environment, and S3-native state locking with use_lockfile = true on Terraform versions that support it. HashiCorp documents the DynamoDB locking argument as deprecated; existing teams may need it for compatibility or a migration period, but new setups should follow the current backend documentation rather than assuming it is simply the standard option for every release before 1.10. Environment separation should come from distinct configurations and state keys. Workspaces can help with short-lived, similar stacks, but they are not an access-control boundary.
A remote backend gives collaborators a shared state location. Locking prevents supported concurrent state-writing operations on the same state from proceeding at once; it does not coordinate application changes or replace review. S3 object versioning gives a recovery history, but restoring a state version still requires care because it must match the real infrastructure.
This guide covers backend setup, access controls, lock behavior, migration from local state, and where workspaces fit. Check the official S3 backend documentation for your Terraform version before applying the examples, because supported arguments and permissions evolve.
What the state file actually is, and why local state fails
Terraform state is a JSON document that records which real objects belong to which resource addresses, along with cached attribute values and outputs. Terraform reads state during planning and updates it during operations that change managed resources. If state is missing or inconsistent with infrastructure, Terraform can propose unintended changes. Recovery depends on the backend, available backups, and what happened to the real resources; do not assume a single command can repair every case.
A local terraform.tfstate file is a poor team coordination mechanism. Two engineers can each work from a stale copy; committing state to a shared branch does not provide atomic updates, locking, or safe recovery. Concurrent applies can create conflicting operations against real infrastructure, while a stale state copy may omit resources created by another run. Losing the only current state requires careful recovery and may require importing resources.
A remote backend provides shared storage. If the backend supports locking, Terraform automatically locks operations that can write state and stops when it cannot obtain a lock. That serializes state-writing operations; it does not merge two configurations or guarantee that a previously reviewed plan remains valid. Re-plan and review after a competing apply. Bucket versioning can provide prior object versions for recovery, but a restored state still needs to match real infrastructure.
One thing worth separating early: .terraform.lock.hcl is not state. It pins provider versions and checksums and belongs in Git. terraform.tfstate is the mapping of your infrastructure and does not belong in Git, ever, including in a private repository. Those two files get confused in code review often enough that it is worth putting a line in the README.
Choosing a backend for a five-person team
Common remote options include S3, Google Cloud Storage, Azure Blob Storage, and HCP Terraform. Backend capabilities, locking behavior, and required IAM permissions vary; check the documentation for the backend and Terraform version you plan to run. For a small team already using AWS, S3 can be a practical fit because the credentials and access model are already familiar. HCP Terraform is another option when managed remote runs and centralized access controls fit the team’s needs.
HashiCorp currently marks DynamoDB-based S3 locking as deprecated. Existing users should follow its migration guidance; it is not presented here as the default for older releases. With any backend, enable locking if supported and verify that the backend access policy permits the lock operations.
If you run OpenTofu, check which backend arguments your installed version supports before copying examples. Do not assume upstream Terraform features and version support match OpenTofu.
Creating the bucket and state key
Bootstrap the bucket outside the configuration that uses it as a backend. Before running commands, confirm the AWS account and Region, and replace the example with a globally unique bucket name you control. The us-east-1 create request omits LocationConstraint; other Regions require it.
set -euo pipefailexport BUCKET=acme-tfstate-prodexport REGION=eu-central-1
aws sts get-caller-identity
if [ "$REGION" = "us-east-1" ]; then aws s3api create-bucket --bucket "$BUCKET" --region "$REGION"else aws s3api create-bucket \ --bucket "$BUCKET" \ --region "$REGION" \ --create-bucket-configuration LocationConstraint="$REGION"fi
aws s3api put-public-access-block \ --bucket "$BUCKET" \ --public-access-block-configuration \ "BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true"
aws s3api put-bucket-versioning \ --bucket "$BUCKET" \ --versioning-configuration Status=Enabled
aws s3api put-bucket-encryption \ --bucket "$BUCKET" \ --server-side-encryption-configuration '{"Rules":[{"ApplyServerSideEncryptionByDefault":{"SSEAlgorithm":"AES256"}}]}'Review the active account and replace the sample bucket name before running this block. It creates persistent cloud resources and configures the named bucket. Amazon S3 applies SSE-S3 by default to new object uploads; the explicit setting above documents that baseline. If policy requires SSE-KMS, create a key in the bucket’s Region, configure encryption, and grant the Terraform role the KMS permissions required by the S3 backend. Validate the key policy before the first apply.
Versioning helps recover from accidental overwrite or deletion, but each stored version incurs storage charges. An optional lifecycle rule can permanently remove noncurrent versions after a retention period you choose. Do not use a generic retention period without checking recovery and compliance requirements:
{ "Rules": [ { "ID": "expire-noncurrent-state", "Status": "Enabled", "Filter": { "Prefix": "" }, "NoncurrentVersionExpiration": { "NoncurrentDays": 90 }, "AbortIncompleteMultipartUpload": { "DaysAfterInitiation": 1 } } ]}Save the reviewed rule as lifecycle.json and apply it only if the retention choice is appropriate:
aws s3api put-bucket-lifecycle-configuration \ --bucket "$BUCKET" \ --lifecycle-configuration file://lifecycle.jsonS3 lifecycle expiration permanently removes expired noncurrent versions. Keep a separate backup strategy if your recovery objectives need longer retention.
Use this partial backend configuration for the example environment:
bucket = "acme-tfstate-prod"key = "platform/prod/terraform.tfstate"region = "eu-central-1"use_lockfile = trueKeep backend settings free of secrets. Supply credentials through an SSO profile, workload role, or another supported credential chain. Run terraform init -backend-config=backend.hcl from the root module directory.
HashiCorp marks DynamoDB-based S3 locking as deprecated. Existing configurations may retain dynamodb_table during a migration, but new setups should use S3 lockfiles where supported. Verify support in the documentation for your installed Terraform version. With native locking, Terraform creates a <key>.tflock object next to the state object; scope permissions to the required state and lock objects.
Wiring the backend into the repository
Keep the backend block partial and pass the environment-specific values at init time. That way the same main.tf works for dev and prod, and nobody edits a bucket name to test something.
terraform { backend "s3" {}}bucket = "acme-tfstate-prod"key = "platform/prod/terraform.tfstate"region = "eu-central-1"use_lockfile = true
# Optional: set these only after creating and authorizing a KMS key.# encrypt = true# kms_key_id = "arn:aws:kms:eu-central-1:111122223333:key/KEY_ID"cd terraform/envs/prodterraform init -backend-config=backend.hclBefore enabling use_lockfile, verify that your installed Terraform version supports it. The S3 backend documentation currently marks dynamodb_table locking as deprecated; if you maintain a legacy configuration that depends on it, follow the documented migration path rather than copying it into a new setup.
backend.hcl contains no secrets, so commit it. Everything in it is an identifier and a region. The credentials come from the environment, from an SSO profile, or from the CI runner’s role, and they never enter the file.
A layout that has held up for teams this size:
terraform/├── bootstrap/ # bucket and optional KMS key; separate bootstrap state├── modules/│ └── network/└── envs/ ├── dev/ │ ├── backend.hcl │ ├── main.tf │ └── terraform.tfvars └── prod/ ├── backend.hcl ├── main.tf └── terraform.tfvarsAdd *.tfstate, *.tfstate.*, .terraform/, and *.tfplan to .gitignore. Add crash.log too, since Terraform writes one on panic and it can contain state fragments.
What locking protects, and what it does not
Locking serializes applies against one state file. It does not make concurrent work safe in any broader sense. Two engineers can still write conflicting changes to the same resource in separate branches, and the second apply will overwrite the first one’s attributes even though the locks were acquired in sequence.
For existing backends using DynamoDB-based locking, HashiCorp requires a string partition key named LockID; consult the backend documentation for all required permissions and migration steps. With native S3 locking, Terraform uses a <key>.tflock object next to the state object. The lock mechanism is separate from version history and does not make stale plans safe to apply.
Both mechanisms depend on the holder releasing the lock. A CI job that gets cancelled mid-apply, a laptop that closes the lid, or a SIGKILL after the lock was taken all leave the lock in place with no owner. Terraform’s exact backend error text varies by backend and version. The following schematic output shows the kind of fields to inspect; the values are placeholders, not a real lock record:
Error: Error acquiring the state lock
Error message: ConditionalCheckFailedException: The conditional request failedLock Info: ID: b7c4e2a1-1f3d-9a6e-2c88-4d1f0a5e7b93 Path: acme-tfstate-prod/env:/prod/platform/terraform.tfstate Operation: OperationTypeApply Who: runner@gha-runner-7f9c Version: 1.11.2 Created: 2026-12-02 08:14:31.9921 +0000 UTC Info:The output above is illustrative, not a real incident record. Inspect the lock information and check whether the owner process or CI run is still active before taking action. An old timestamp alone does not prove the lock is stale. If you confirm that no operation is running and automatic unlocking failed, use the exact lock ID reported by Terraform with terraform force-unlock <LOCK_ID>. This removes the lock; it does not stop a process. Unlocking while an apply is still active can permit competing writers and corrupt state.
Where practical, pass -lock-timeout=10m to plan and apply so Terraform waits for a lock. This does not guarantee a queued operation’s plan remains current; review the resulting plan before applying. A CI concurrency group can reduce overlapping runs from one workflow but cannot cover other workflows or operator commands.
-lock=false disables locking for that command and should not be used for a shared state unless you have deliberately established that no other writer can operate at the same time. Do not use it as a routine workaround or alongside a shared-state apply.
Moving the existing local state
Run the migration on the machine that holds the only current copy, and take a backup first.
State files can contain sensitive values. Use a private directory with restrictive permissions, and ensure the backup is encrypted and access-controlled:
umask 077mkdir -p "$HOME/terraform-state-backups"chmod 700 "$HOME/terraform-state-backups"cd terraform/envs/prodterraform state pull > "$HOME/terraform-state-backups/prod-before-migration.tfstate"Store the backup only in an approved encrypted location with restricted access. Do not upload it to a broadly readable bucket or commit it to version control. Keep it until the new backend is verified and the recovery window allows deletion.
Then add the backend "s3" {} block, create backend.hcl, and run:
terraform init -migrate-stateTerraform detects the existing local state and asks whether to copy it to the new backend. Answer yes. If you already ran init with a different backend configuration and need to switch, terraform init -reconfigure re-reads the configuration without touching state, which is the right choice when state already lives remotely and you only changed the key prefix.
Verify before the next apply. terraform state list should print the same resource count as before, and terraform plan should return no changes. A non-empty plan immediately after migration means the backend is pointing at a different state file than the one you copied, or the copy was skipped. Find out which before applying.
Then remove the file from version control without deleting it locally:
git rm --cached terraform.tfstategit commit -m "Stop tracking Terraform state"Everyone else on the team needs to pull and run terraform init -backend-config=backend.hcl in that directory. Their local terraform.tfstate files are now dead weight; deleting them is safe once the remote state is verified.
CLI workspaces: useful, but not environment isolation
CLI workspaces let one configuration and backend track multiple state instances. They share the backend setup and authentication context; a workspace name does not create separate credentials or access controls. HashiCorp explicitly advises against using workspaces for deployments that need separate credentials or system decomposition. For dev and prod, use separate root configurations and state keys, and separate roles or cloud accounts when access boundaries require them.
Workspace commands are straightforward:
terraform workspace listterraform workspace new preview-482terraform workspace select preview-482terraform workspace showWith the S3 backend, the default workspace uses the configured key. Other workspaces use <workspace_key_prefix>/<workspace_name>/<key>; the default prefix is env:. This path layout is not a security boundary. If IAM allows a role to read all matching workspace objects, switching workspace does not narrow those permissions.
Workspaces can suit multiple instances of the same configuration when they intentionally share credentials and access policy, such as disposable preview stacks. In automation, select the intended workspace explicitly, validate the environment, and review the plan before applying or destroying resources. Avoid deriving production safeguards solely from terraform.workspace; a mistaken selection can target another state under the same credentials.
Do not use terraform workspace delete -force as cleanup. It removes the workspace state without destroying the infrastructure, which can leave unmanaged resources behind. If the infrastructure should be removed, plan and apply a destroy operation first, verify the resources are gone, then delete the empty workspace.
Reading outputs across states
Once environments have separate state files, the prod network state needs the VPC ID that the network configuration created. The terraform_remote_state data source reads it directly:
data "terraform_remote_state" "network" { backend = "s3"
config = { bucket = "acme-tfstate-prod" key = "platform/prod/network/terraform.tfstate" region = "eu-central-1" }}
resource "aws_instance" "api" { subnet_id = data.terraform_remote_state.network.outputs.private_subnet_id}The config argument is a backend configuration object; it does not accept a path to the root module’s backend.hcl as a shortcut. Keep the required backend settings explicit in this data source, or use another documented mechanism to supply values without putting credentials in configuration.
Treat this data source as a security boundary. Although Terraform exposes only root outputs to expressions, a principal that can read those outputs through terraform_remote_state can also read the full state snapshot from the backend. Do not use it to share outputs when the source state contains sensitive data and the consumer should not have access to that data. Prefer publishing the specific required values to a separately controlled store, such as SSM Parameter Store or DNS, and grant consumers access only to those values.
There is also configuration coupling. Each referenced output becomes an interface: removing or renaming one can break the consumer’s plan. Keep dependencies one-directional—for example, network configuration publishes identifiers and application configuration consumes them—and avoid circular references between state files.
IAM, and the secrets sitting in plain sight
State contains attribute values, and some providers store sensitive values in state as plaintext: generated database passwords, tls_private_key output, and the full body of some secrets. Encryption at rest with KMS is necessary but not sufficient. Restrict who can read the bucket, and log those reads.
For the example’s default workspace and key platform/prod/terraform.tfstate, the backend role needs s3:ListBucket on the bucket scoped to that state path, s3:GetObject and s3:PutObject on the state object, and s3:GetObject, s3:PutObject, and s3:DeleteObject on its .tflock object. The following is a starting point for the default workspace only; validate the prefix condition and exact permissions against the current backend documentation and your AWS policy tooling before deployment.
{ "Version": "2012-10-17", "Statement": [ { "Sid": "ListStatePrefix", "Effect": "Allow", "Action": "s3:ListBucket", "Resource": "arn:aws:s3:::acme-tfstate-prod", "Condition": { "StringLike": { "s3:prefix": ["platform/prod/terraform.tfstate"] } } }, { "Sid": "ReadWriteState", "Effect": "Allow", "Action": ["s3:GetObject", "s3:PutObject"], "Resource": "arn:aws:s3:::acme-tfstate-prod/platform/prod/terraform.tfstate" }, { "Sid": "ManageStateLock", "Effect": "Allow", "Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"], "Resource": "arn:aws:s3:::acme-tfstate-prod/platform/prod/terraform.tfstate.tflock" } ]}This example is for one key and the default workspace only. If using workspaces, add the documented workspace-state and lock-object paths to the policy; do not assume the policy above covers them. Terraform does not need s3:DeleteObject on the state object for normal S3 backend use. Keep bucket administration and policy changes in a separate role.
S3 now applies SSE-S3 by default. If you choose a customer-managed KMS key, create it in the bucket’s Region and grant the backend role the KMS permissions required by the S3 backend, including decrypt and data-key generation. A KMS key alias must already exist and be usable by that role; the example alias is not created by the bucket commands. Follow the AWS and HashiCorp documentation for the exact key policy and permissions rather than relying on an assumed default.
Running Terraform in CI with a review gate
A small team can run Terraform from laptops or CI. The important controls are to protect backend credentials, keep backend locking enabled, and require a human review before production changes. A CI concurrency group can avoid overlapping runs from one workflow, but it does not replace backend locking or prove that a plan remains current after approval.
For GitHub Actions with AWS, use OIDC to assume short-lived roles instead of storing long-lived access keys. Give pull-request plan jobs only the permissions they need, and do not allow untrusted fork code to assume a role that can read production state. A plan job may need read access to the state and can reveal sensitive values in plan output, so restrict where that output is posted and who can access it. Use a distinct, protected role for apply; configure GitHub environment approvals or an equivalent control for production.
Before apply, ensure the reviewed plan belongs to the intended commit and state. A saved plan can become stale if another operation changes state; Terraform rejects a stale saved plan. Recreate and review the plan rather than bypassing the protection. Treat saved plan files as sensitive artifacts: restrict access and set a short retention period.
Keep the remote backend lock enabled even when CI runs are serialized. The backend protects the state from concurrent state-writing Terraform operations, including runs started outside that workflow. If the team cannot yet implement a reviewed CI apply flow, permit manual applies only through the team’s documented approval process and keep the same backend lock in place.
Troubleshooting the errors you will actually see
Error: error configuring S3 Backend: no valid credential sources for S3 Backend found. The backend runs before provider configuration, so an assume_role block in the AWS provider does nothing for it. Pass AWS_PROFILE or AWS_ROLE_ARN, or use -backend-config with an explicit role assumption. This trips up every team that moves to a named profile.
Error: Failed to get existing workspaces: S3 bucket does not exist. Either the bucket name in backend.hcl is wrong or your credentials point at another account. Cross-check with aws s3api head-bucket --bucket acme-tfstate-prod using the same profile the init used.
Error: Backend initialization required, please run "terraform init" after editing the backend block is normal. Run terraform init -reconfigure if the state location did not change, or -migrate-state if it did.
Error: state snapshot was created by Terraform v1.11.2, which is newer than current v1.9.8; upgrade to Terraform v1.11.2 or greater to work with this state means a laptop is behind the version CI uses. Pin the version in the pipeline and in a .terraform-version file, and stop letting people apply with whatever brew last installed.
A corrupted state object usually announces itself as a JSON parse error during plan. Recover it from versioning rather than editing by hand:
aws s3api list-object-versions \ --bucket acme-tfstate-prod \ --prefix platform/prod/terraform.tfstate \ --query 'Versions[?IsLatest==`false`].[VersionId,LastModified]' \ --output table
# Replace VERSION_ID with a value returned by the command above.aws s3api get-object \ --bucket acme-tfstate-prod \ --key platform/prod/terraform.tfstate \ --version-id VERSION_ID \ /tmp/terraform.tfstate.candidateDo not immediately push a downloaded version back to the live key. First stop applies, confirm the selected version and its timestamp with the team, and preserve a copy of the current state. Validate the candidate JSON and compare its lineage and serial with the current state. Then follow HashiCorp’s documented recovery procedure for your backend and Terraform version; terraform state push has lineage and serial safeguards, and -force bypasses them. A mismatch can roll state backward or detach real resources, so use -force only as a deliberate, reviewed recovery action, never as a routine fix.
A practical baseline
For an AWS team, start with a private S3 bucket, versioning, a distinct state key for each root configuration, and S3-native locking when supported by the Terraform version in use. Use separate credentials or accounts where production requires an access boundary. Keep state and lock-object permissions narrow, and treat plans and state backups as sensitive data.
Locking prevents supported concurrent writes to the same state; it does not resolve conflicting code changes, stale plans, incorrect workspace selections, or permissions that are too broad. Use review gates, validate the target environment, and re-plan when state changes. Test state recovery before an incident, and keep lifecycle retention aligned with the team’s recovery and compliance requirements.
For exact backend arguments and permission paths, use the official documentation for the Terraform version and backend you deploy. Treat examples in this guide as starting points to review—not commands to run against an unverified production account.