How to store Terraform state in S3 with native lockfile locking, bootstrap the state bucket, migrate local state, split state per environment, grant the right IAM permissions and recover a bad state file, plus how application infrastructure can be provisioned from code.

Terraform keeps a state file that maps every resource in your configuration to a resource ID in AWS, and on a laptop that file is terraform.tfstate in the working directory. It stops working the day a second person or a CI job runs apply, since each has its own copy.
The S3 backend moves state into a bucket where every run reads the same copy, and since Terraform 1.11 it can lock that copy with a lock file next to the state object instead of a DynamoDB table, so two applies cannot run at once. This guide covers the setup, migration, permissions and recovery.
The backend block names the bucket, the object key for this configuration's state and the region, and use_lockfile = true turns on locking. The S3 backend docs also recommend bucket versioning so an overwritten state can be recovered:
# backend.tf
terraform {
required_version = ">= 1.11"
backend "s3" {
bucket = "acme-terraform-state"
key = "platform/network/terraform.tfstate"
region = "eu-central-1"
encrypt = true
use_lockfile = true
}
}
With use_lockfile, Terraform writes a terraform.tfstate.tflock object next to the state before it changes anything and deletes it afterwards, using an S3 conditional write so that only one run can create it. A second apply that starts in the meantime fails with a lock error instead of writing over the first one. Backend blocks cannot use variables, so values that differ per environment go into a partial configuration passed at init time, such as terraform init -backend-config=prod.s3.tfbackend.
The state bucket has to exist before any configuration can use it, which makes it the one piece of infrastructure Terraform cannot comfortably manage with a remote backend. The usual answer is a small bootstrap configuration with local state, applied once, that creates the bucket with versioning, encryption and public access blocked:
# bootstrap/main.tf
resource "aws_s3_bucket" "state" {
bucket = "acme-terraform-state"
lifecycle {
prevent_destroy = true
}
}
resource "aws_s3_bucket_versioning" "state" {
bucket = aws_s3_bucket.state.id
versioning_configuration {
status = "Enabled"
}
}
resource "aws_s3_bucket_server_side_encryption_configuration" "state" {
bucket = aws_s3_bucket.state.id
rule {
apply_server_side_encryption_by_default {
sse_algorithm = "aws:kms"
}
}
}
resource "aws_s3_bucket_public_access_block" "state" {
bucket = aws_s3_bucket.state.id
block_public_acls = true
block_public_policy = true
ignore_public_acls = true
restrict_public_buckets = true
}
State files hold every attribute Terraform reads back from AWS, including database passwords set through Terraform and private keys from resources such as tls_private_key, so treat read access to this bucket like read access to your secrets. Some teams move the bootstrap state into the bucket afterwards with a second init -migrate-state, and others keep it local in a locked-down repository, since it changes about once a year.
Add the backend block to a configuration that already has a local terraform.tfstate, then run init with the migrate flag. Terraform detects the backend change, asks whether to copy the existing state and writes it to the new key:
An empty plan afterwards confirms that the migrated state matches the resources. Delete or archive the local terraform.tfstate and terraform.tfstate.backup files once the plan is clean, since a later terraform run in a directory with a stale local file and no backend block would silently use it. Moving from DynamoDB locking works the same way: set use_lockfile = true next to the existing dynamodb_table, run terraform init -reconfigure, and remove dynamodb_table after every pipeline uses a Terraform version with lockfile support.
One state object for everything means every plan reads every resource, and a mistake in a staging change can lock out a production fix. A key per component and environment keeps plans small and limits what one apply can break:
Separate keys also let the IAM policy follow the layout, so the role CI uses for staging can only write staging/* and the production role lives in the production account.
The backend needs s3:ListBucket on the bucket, s3:GetObject and s3:PutObject on the state key, and s3:GetObject, s3:PutObject and s3:DeleteObject on the .tflock key when lockfile locking is on. Terraform never deletes the state file itself, so the role does not need delete permission on it:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "s3:ListBucket",
"Resource": "arn:aws:s3:::acme-terraform-state",
"Condition": { "StringLike": { "s3:prefix": "prod/network/*" } }
},
{
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:PutObject"],
"Resource": "arn:aws:s3:::acme-terraform-state/prod/network/terraform.tfstate"
},
{
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
"Resource": "arn:aws:s3:::acme-terraform-state/prod/network/terraform.tfstate.tflock"
}
]
}
With SSE-KMS, the same role also needs kms:Encrypt, kms:Decrypt and kms:GenerateDataKey on the key, or every init fails with an access denied error that looks like an S3 problem. The S3 access denied guide walks through reading those errors.
A lock left behind by a cancelled CI job blocks every later run until it is removed. Check that nothing is still running, then release it with terraform force-unlock LOCK_ID, using the ID from the error message, as the state lock error guide explains.
A state file that was overwritten by a bad terraform state rm, an old Terraform version or a hand edit is where bucket versioning pays for itself. S3 Versioning keeps every earlier write of the key, so you can list the versions, download the one from before the mistake and push it back:
terraform state push refuses a state with a lower serial than the current one unless you add -force, which is a useful check that you picked the version you meant. Run a plan right after and compare it with what you expect before applying anything.
Encore brings infrastructure from code, so the database, topic and bucket a service uses are declared next to the handlers that use them, and Encore works out what to provision in your AWS account from the code on each deploy. There is no state bucket to bootstrap for those resources, no lock to release after a cancelled run and no state file holding database passwords. The Encore platform keeps a versioned infrastructure graph linked to each deployment and git commit, and it reads current resource properties before changing anything, as the managing infrastructure docs describe.

Run in your terminal to get started locally.
A service that stores orders in Postgres and announces each one on a topic for other services:
// orders/encore.service.ts
import { Service } from "encore.dev/service";
export default new Service("orders");
The migration for the orders table:
-- orders/migrations/1_orders.up.sql
CREATE TABLE orders (
id BIGSERIAL PRIMARY KEY,
customer_id TEXT NOT NULL,
total_cents BIGINT NOT NULL CHECK (total_cents >= 0),
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
Then the endpoints:
// orders/orders.ts
import { api, APIError } from "encore.dev/api";
import { SQLDatabase } from "encore.dev/storage/sqldb";
import { Topic } from "encore.dev/pubsub";
const db = new SQLDatabase("orders", { migrations: "./migrations" });
export interface OrderPlaced {
orderID: number;
customerID: string;
totalCents: number;
}
export const orderPlaced = new Topic<OrderPlaced>("order-placed", {
deliveryGuarantee: "at-least-once",
});
export const place = api(
{ expose: true, method: "POST", path: "/orders" },
async (p: { customerID: string; totalCents: number }): Promise<{ id: number }> => {
if (!p.customerID || !Number.isInteger(p.totalCents) || p.totalCents < 0) {
throw APIError.invalidArgument("customerID and a non-negative integer totalCents are required");
}
const row = await db.queryRow<{ id: number }>`
INSERT INTO orders (customer_id, total_cents)
VALUES (${p.customerID}, ${p.totalCents})
RETURNING id
`;
await orderPlaced.publish({ orderID: row!.id, customerID: p.customerID, totalCents: p.totalCents });
return { id: row!.id };
},
);
encore run starts Postgres locally, applies the migration and runs the topic in process, so the endpoint can be tried right away. On deploy to your AWS account, Encore provisions RDS for the database, SNS and SQS for the topic and an IAM role for the service.
Terraform does not have to go away for this, and the network, DNS and account setup that other teams own can stay in the S3 backend described above. The Encore Terraform provider has data sources such as encore_pubsub_topic, so a Terraform configuration can wire another AWS service to the topic Encore created:
data "encore_pubsub_topic" "order_placed" {
name = "order-placed"
env = "prod"
}
output "order_placed_sns_arn" {
value = data.encore_pubsub_topic.order_placed.aws_sns.arn
}
A coding agent that adds a refunds table or a second topic changes the service code in one diff and runs it locally, with no state file it has to read and no backend credentials in its environment.
Best fit: Teams that keep shared AWS foundations in Terraform and want each service's databases, topics and buckets to deploy from the application repository.
use_lockfile = true and drop dynamodb_table once every pipeline is on Terraform 1.11 or later..tflock objects.terraform init -migrate-state and confirm with an empty plan.terraform state push, then plan before applying.No. Terraform 1.11 and later let the S3 backend lock with a lock file next to the state object when you set use_lockfile = true. The argument first appeared in 1.10, DynamoDB locking with dynamodb_table is deprecated, and both can be configured together while you migrate.
Add a backend "s3" block with the bucket, key and region, then run terraform init -migrate-state. Terraform asks whether to copy the existing state to the new backend, and after it confirms, terraform plan should show no changes.
s3:ListBucket on the bucket, s3:GetObject and s3:PutObject on the state key, and with use_lockfile also s3:GetObject, s3:PutObject and s3:DeleteObject on the key with a .tflock suffix. Terraform does not need delete permission on the state file itself.
With bucket versioning turned on beforehand, list the versions of the state key with aws s3api list-object-versions, download the last good one and push it back with terraform state push, or copy that version over the current object.
No. Encore provisions databases, topics and buckets declared in application code in your own AWS or GCP account, so those resources do not live in a Terraform state file. A shared S3 backend remains useful for foundations you still manage with Terraform, such as a VPC.
Deploy to your cloud on AWS and Google Cloud
without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.