Remote Backends: S3 & Locking
A terraform.tfstate on your laptop works for one person. A team needs the state in one shared place, protected against two people writing it at once, versioned so a bad write can be undone, and encrypted because it holds secrets. A backend is that place. On AWS the standard choice is an S3 bucket, with locking either through a lock file in the same bucket (the current way) or a DynamoDB table (the older way).
The backend block
terraform {
backend "s3" {
bucket = "acme-tfstate-123456789012-eu-west-1"
key = "linkly/network/prod.tfstate" # one key per state
region = "eu-west-1"
encrypt = true # server-side encryption of the object
use_lockfile = true # S3-native locking: writes prod.tfstate.tflock next to it
}
}| Argument | Notes |
|---|---|
bucket, key, region |
where the state object lives; key is the path inside the bucket |
encrypt |
SSE for the state object; add kms_key_id for a customer-managed KMS key |
use_lockfile |
S3-native locking with a conditional write of <key>.tflock. Terraform 1.11+ and OpenTofu 1.10+ |
dynamodb_table |
the older locking: a DynamoDB table with a LockID string partition key. Terraform marks it deprecated in favour of use_lockfile; OpenTofu supports both and has no plans to drop either. Both can be enabled at once while you migrate |
workspace_key_prefix |
where non-default workspaces store their state (env: by default, so env:/staging/<key>) |
assume_role { role_arn = … } |
access the state bucket through a role in another account |
The backend block is special: it is read during init, before variables exist, so in Terraform it can't use var. or local. at all. Values that differ per environment come from partial configuration files instead (OpenTofu 1.8+ can also evaluate variables and locals there, see OpenTofu):
# backend/prod.s3.tfbackend
bucket = "acme-tfstate-123456789012-eu-west-1"
key = "linkly/network/prod.tfstate"
region = "eu-west-1"
use_lockfile = truetofu init -backend-config=backend/prod.s3.tfbackendBootstrapping the state bucket
The bucket has to exist before any configuration can store state in it: a chicken-and-egg problem usually solved with one small "bootstrap" configuration, applied once with local state (or created by your account-vending process). Here it is, planned offline with the teaching provider setup:
mkdir bootstrap && cd bootstrap
cat > offline.tf <<'HCL'
provider "aws" {
region = "eu-west-1"
access_key = "offline"
secret_key = "offline"
skip_credentials_validation = true
skip_requesting_account_id = true
skip_metadata_api_check = true
}
HCL
cat > main.tf <<'HCL'
terraform {
required_providers {
aws = { source = "hashicorp/aws", version = "~> 6.0" }
}
}
variable "bucket_name" {
type = string
default = "acme-tfstate-123456789012-eu-west-1"
}
resource "aws_s3_bucket" "state" {
bucket = var.bucket_name
lifecycle {
prevent_destroy = true
}
}
resource "aws_s3_bucket_versioning" "state" {
bucket = aws_s3_bucket.state.id
versioning_configuration {
status = "Enabled" # every state write is a new version: undo a bad write
}
}
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
}
HCL
tofu init >/dev/null
tofu validate
tofu plan | grep -E '^ #|^Plan:'Success! The configuration is valid.
# aws_s3_bucket.state will be created
# aws_s3_bucket_public_access_block.state will be created
# aws_s3_bucket_server_side_encryption_configuration.state will be created
# aws_s3_bucket_versioning.state will be created
Plan: 4 to add, 0 to change, 0 to destroy.
Add a bucket policy that denies non-TLS access and limits who can read the state, and consider aws_s3_bucket_lifecycle_configuration to expire old noncurrent versions after a few months. The S3 lessons of the AWS course explain those settings.
Validating a configuration with a remote backend, offline
init normally contacts the backend. -backend=false skips it, which is how CI lint jobs validate code without state access:
mkdir app && cd app
cat > main.tf <<'HCL'
terraform {
required_providers {
aws = { source = "hashicorp/aws", version = "~> 6.0" }
}
backend "s3" {
bucket = "acme-tfstate-123456789012-eu-west-1"
key = "linkly/app/prod.tfstate"
region = "eu-west-1"
use_lockfile = true
}
}
resource "aws_sqs_queue" "jobs" {
name = "linkly-jobs"
}
HCL
tofu init -backend=false | grep -E 'Initializing|Installed|initialized'
tofu validateInitializing provider plugins...
- Installed hashicorp/aws v6.70.0 (unauthenticated)
OpenTofu has been successfully initialized!
Success! The configuration is valid.
A real init and plan against S3
With credentials, init connects to the bucket. A sample session (output trimmed):
$ tofu init -backend-config=backend/prod.s3.tfbackend
Initializing the backend...
Successfully configured the backend "s3"! OpenTofu will automatically
use this backend unless the backend configuration changes.
…
$ tofu plan
Acquiring state lock. This may take a few moments...
aws_sqs_queue.jobs: Refreshing state... [id=https://sqs.eu-west-1.amazonaws.com/123456789012/linkly-jobs]
No changes. Your infrastructure matches the configuration.
Releasing state lock. This may take a few moments...While the plan runs, the bucket holds linkly/app/prod.tfstate.tflock; with dynamodb_table the lock is an item in the table instead. The next lesson shows what happens when two runs collide.
Other backends
| Backend | Where |
|---|---|
gcs |
Google Cloud Storage, locking built in |
azurerm |
Azure Blob Storage, locking with blob leases |
pg |
a PostgreSQL database |
kubernetes |
a Secret in a cluster |
http |
any REST endpoint (GitLab's managed Terraform state uses it) |
remote / cloud block |
HCP Terraform or a compatible service (Spacelift, env0, Scalr…) |
The rules are the same everywhere: versioning, encryption, locking, least-privilege access, and one state per environment and component.
Test yourself
What does use_lockfile = true in an S3 backend do?
- Stores the state in DynamoDB
- Locks the state with a
.tflockobject in the same bucket, without DynamoDB - Encrypts the state
- Makes the state read-only
Why can't the Terraform backend block use var.environment?
- Backends don't support strings
- The backend is configured during init, before variables are evaluated
- It can, since 1.0
- Variables are encrypted
Which S3 bucket setting lets you recover from a corrupted state write?
- Transfer acceleration
- Versioning
- Static website hosting
- Requester pays