Back to Terraform

Terraform State on R2: Bootstrap, Locking and Recovery Evidence

November 6, 2026 Wasil Zafar 29 min read

Evaluate the S3-compatible backend with exact client behavior and recovery requirements rather than copying a legacy snippet

Table of Contents

  1. The S3 Backend Is Independent of the Cloudflare Provider
  2. Bootstrap State Storage with a Different Recovery Owner
  3. Test Native Lockfile Behavior on the Selected R2 Endpoint
  4. Do Not Assume AWS Bucket Versioning Exists on R2
  5. Migrate State with the Correct Init Semantics
  6. Demonstrate Lock Contention and Snapshot Restoration

The S3 Backend Is Independent of the Cloudflare Provider

One working directory, two clients that never share a configuration path. The backend block is read by code compiled into the Terraform binary; the Cloudflare provider is a plugin installed into the working directory. The backend resolves during init, before any provider is downloaded, so the two fail for different reasons and are repaired by different changes.

The credentials are not interchangeable. The provider authenticates to the Cloudflare API with an API token scoped to account resources. The backend authenticates to R2's S3 endpoint with an R2 access key pair, which the CLI reads through the standard AWS credential chain.

The endpoint is a hostname, not a region. R2 answers S3 calls at a per-account host, and the region value is auto; an empty value and us-east-1 alias to it for tools that insist on a region. Getting the endpoint right is an init-time concern, not an apply-time one.

Version drift splits along that line too. A CLI upgrade can change backend behavior — checksum headers, retry policy, lockfile support — while the provider stays pinned to 5.28.1. The reverse is also true: bumping the provider cannot repair an init that cannot reach the endpoint.

The merged configuration is written down. Terraform records the resolved backend settings inside the working directory and copies them into saved plan files, in plain text. An access key placed in the backend file therefore lands in two more places; keep keys in the environment and only bucket, key, endpoint and flags in the file.

The endpoint setting has a current spelling. Use the endpoints map rather than the deprecated single-endpoint argument, and set the region guard beside it. A backend file copied from an older AWS guide usually carries the old spelling and a region that R2 will reject.

The collision lives in the environment. The backend reads the standard AWS credential variables, and so does an AWS provider if one is present. Exporting R2 keys for the backend therefore hands them to that provider in the same shell; use a named profile or a scoped wrapper instead of a global export.

Init order is the operational consequence. A root with a wrong bucket name, a wrong key or an expired key fails before a plan exists. Editing the provider block cannot help, because the provider has not been installed yet.

Two initializations tell you which side is broken. Initializing with the backend disabled installs providers and leaves state alone; a normal init exercises the store. If the first succeeds and the second fails, the fault is in the backend settings, not the configuration.

LayerClientCredentialVersion it followsFirst failure
State read and writeS3 backend inside the CLIR2 access key pairTerraform CLIterraform init
Lock objectS3 backend inside the CLISame R2 key pairTerraform CLIFirst locked operation
Bucket and policyCloudflare providerCloudflare API tokenProvider releasePlan or apply
Snapshot and restoreSeparate toolingSnapshot-store credentialYour runbookRecovery, not apply

Figure 1 separates the two paths and places each failure where a reader will meet it.

The S3 Backend Is Independent of the Cloudflare Provider
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    I["terraform init"] --> B["Backend block
s3, built into the CLI"] B --> P["Provider install
cloudflare 5.28.1"] B --> E["R2 S3 endpoint
region auto"] E --> K["R2 access key
from the environment"] K --> S["State object and lock object"] P --> T["Cloudflare API token"] T --> A["Cloudflare API"] A --> C["cloudflare_r2_bucket"] C -. "bootstrap only" .-> S E -. "missing or wrong key" .-> F1["init fails before providers"] A -. "missing scope" .-> F2["plan or apply fails"] classDef primary fill:#132440,color:#ffffff,stroke:#0b172b; classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a; classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f; classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420; classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f; class I,B,E,K,S primary; class P,T,A,C secondary; class F1 danger; class F2 warn;

The dashed edge is the bootstrap problem. The provider can create the bucket the backend needs, but not from the root whose state lives inside it. That ordering gets its own section.

Figure 2 draws the same split as a boundary, because the two credentials have different blast radii.

The S3 backend and the Cloudflare provider use separate clients, endpoints and credentials The Terraform CLI contains the S3 backend, which uses an R2 access key against the R2 S3 endpoint to read and write state and lock objects. The Cloudflare provider plugin uses an API token against the Cloudflare API to manage the bucket and its policy. The bucket is created once at bootstrap, and a backend failure occurs before the provider is installed. Two clients, two credentials The backend resolves before the provider is installed. Terraform CLI 1.17.1 S3 backend (built in) reads and writes one state object creates the adjacent lock object follows the CLI release cloudflare provider installed as a plugin creates the bucket and policy pinned to 5.28.1 R2 S3 endpoint <account>.r2.cloudflarestorage.com region auto state and lock objects live here Cloudflare API bucket name, jurisdiction, lifecycle CORS and custom domain account-scoped token S3 calls + R2 key pair REST calls + API token state bucket: one key per root, one lock per key creates at bootstrap A backend failure appears before any provider is installed; a provider failure appears after.

Review them separately. A pull request that changes only the provider version cannot move state; a pull request that touches the backend block always can. Treat the second as an operational change with a snapshot and a migration plan, not as configuration cleanup.

Bootstrap State Storage with a Different Recovery Owner

The bucket is infrastructure, and the root that stores state in it cannot create it. The first init needs a bucket that does not exist yet. If the same root creates that bucket, the first init has nowhere to write; if a later destroy removes it, the record of everything else goes with it.

The way out is a bootstrap root with local state. It creates the bucket and its policy, applies once, then moves its own small state into a dedicated prefix. After that the bootstrap root is read rarely and changed carefully.

Terraform cannot close that loop in one apply. The bucket must exist before the backend can write the state that records the bucket, and the dependency graph cannot express that ordering across the backend boundary. A separate root makes the order explicit and keeps the bucket out of a workload's destroy path.

Create the bucket through the Cloudflare API, not the S3 API. The provider resource sets name and jurisdiction deliberately; S3 can create a bucket too, but it will not give you the lifecycle and CORS resources that belong in the same review. Name and jurisdiction are identity, not labels.

Jurisdiction is fixed when the bucket is born. R2 does not move an existing bucket between jurisdictions, so this bootstrap decision is permanent. Record it beside the bucket name and the recovery owner, because a later edit plans a replacement rather than an update.

Prefixes carry ownership. bootstrap/ holds the state of the root that owns the bucket, while network/prod/ holds a workload. Different keys mean independent state even inside one bucket, and a per-prefix credential is a smaller blast radius than a bucket-wide one.

The recovery owner must be a different person or team from the apply owner. That owner holds the snapshot repository, the restore runbook and the authority to refuse a restore with no evidence. Naming the same on-call rotation for both jobs recreates the failure the split was meant to prevent.

Recovery evidence is external, because R2 has no bucket versioning. That is not a detail to defer; it changes what "restore" means and gets a section of its own. Plan the snapshot before the first apply, not after the first bad one.

The runbook names four things. Who may authorize a restore, which snapshot store to read, how to verify lineage afterwards, and who to tell. A runbook without an authorizer becomes a debate in the middle of the incident.

The bootstrap root needs its own identity. It creates buckets and policies, so it should hold a credential that workload roots never receive. A separate API token with an expiry and a separate R2 key keep the bucket administrator out of daily applies.

Compatibility flags are narrow, and each needs a reason. The settings that suppress AWS-only validation calls exist because the endpoint answers neither STS nor IAM, and its checksum surface differs from AWS; none of them relaxes authentication or encryption. Keep them beside the endpoint, not in a global shell profile where another root inherits them by accident.

One lifecycle rule can erase the argument. A rule with an empty prefix covers the whole bucket, including state and lock objects, and deletion is asynchronous but final. Scope rules to artifact prefixes and keep the state prefix out of every expiry rule.

Bootstrap state is still state. It names the bucket, the policy and the recovery role, and it can contain identifying detail. Leaving it on a laptop after the migration makes one machine the only record of the store; committing it is worse.

Bootstrap State Storage with a Different Recovery Owner
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    L["bootstrap root
local state"] --> C["cloudflare_r2_bucket
created through the Cloudflare API"] C --> P["Prefixes
bootstrap/, network/prod/, network/dev/"] P --> M["init -migrate-state
bootstrap state moves into the bucket"] M --> W["workload roots
one key and one lock each"] W --> S["snapshot job
pull, hash, copy out"] S --> R["recovery owner
restore runbook and drill"] C -. "bucket destroyed" .-> F1["state and bucket lost together"] W -. "empty-prefix lifecycle rule" .-> F2["state object expires"] M -. "bootstrap state kept on a laptop" .-> F3["one machine is the only record"] S -. "copy never restored" .-> F4["backup exists, recovery does not"] classDef primary fill:#132440,color:#ffffff,stroke:#0b172b; classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a; classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f; classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420; classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f; class L,M,W primary; class C,P,S secondary; class R ok; class F1,F3,F4 danger; class F2 warn;

Two failures are loud; two are quiet. A deleted bucket takes its state with it, and an expired key stops init immediately. A lifecycle rule that matches the state prefix and a bootstrap state left only on a workstation both look fine until the day they are needed.

The test is a restore, not a backup job. A weekly job that copies state and never restores it proves that the copy ran and nothing else. Schedule one restore into a scratch key per quarter and record the result next to the runbook.

Test Native Lockfile Behavior on the Selected R2 Endpoint

Locking is opt-in, and the default is off. Set use_lockfile = true on the backend or two concurrent applies will proceed, with the last write deciding which changes survive in state.

The native design is a create-once object. Terraform asks the endpoint to create <key>.tflock only if it does not already exist. The first writer succeeds; the second gets a precondition failure that becomes the familiar lock error.

The error block is the interface. Terraform reports the path, operation, holder and creation time, plus a lock ID. Those fields are how a second engineer confirms that the lock belongs to the run they think it does.

The object has no timer. Nothing in the backend expires a lock; it is deleted when the operation ends, which is why a killed process leaves an object that outlives its run. That is also why the age of the lock is evidence rather than a countdown.

R2 documents the primitive that design needs. Conditional writes on a put are evaluated atomically with the write, so concurrent creations of an absent key produce one success and a failure for the rest. That is exactly the shape of a lock acquisition.

A documented primitive is not a qualified backend. The inference is reasonable, but the client must issue that write against this endpoint and the delete path must work afterwards. Only a second writer proves the whole loop.

Do not carry the DynamoDB assumption across. DynamoDB is an AWS service; dynamodb_table in an R2 backend points the CLI at an endpoint that does not exist. The mechanism is also deprecated, so a copied snippet is both broken here and on its way out.

The test needs contending writers, not a queue. Two terminal sessions, one key, one root. A CI queue serialises the jobs it knows about; it cannot stop a manual apply, another repository or a retired runner from reaching the same object.

Lock scope is one key. Two roots with different keys never contend, so a successful two-writer test on the production key says nothing about a staging key with different flags. Repeat the test wherever the backend settings differ.

Observe the object with a plain S3 client. The AWS CLI works against R2 once the endpoint and region are set, so a head request can confirm the lock without going through Terraform. One reading while the first writer runs and one after it exits form the pair.

Collect three facts while the lock is held. The second writer's non-zero exit and error block, the lock object's existence at the start and end of the first operation, and the lock ID and holder named in the error. One screenshot is not the set.

The acceptance rule is short. If you have not watched a second writer get rejected by the backend, you have a configuration, not a lock.

Figure 3 keeps the documented guarantee and the test evidence in one frame.

A create-once lock object rejects the second writer and leaves evidence R2 documents atomic conditional puts, and Terraform must still prove that its client uses one. Writer A applies and creates the lock object, writer B plans with a zero lock timeout and receives a precondition failure that Terraform reports as a state lock error. The evidence is the non-zero exit, the lock object present during the run and absent after it, and the recorded lock ID. Create-once is the whole lock R2 documents conditional puts commit atomically one winner, the rest get a precondition failure Terraform must prove its client performs a create-once write and deletes the object when the run ends writer A apply in terminal 1 holds the lock lock object <key>.tflock created once deleted on release writer B plan, zero lock timeout refused, not queued create create, second A: proceeds and releases B: lock error, exit non-zero Evidence to record 1. second writer's exit status and lock block 2. lock object present at start, absent at end 3. lock ID, holder, operation and creation time 4. the same key and endpoint for both writers

Stale locks are the other half. A killed runner leaves the object behind, and the next run reports a lock that no live process owns. The evidence for clearing it is the same set: holder, age, operation and an independent check that the job is gone.

Do Not Assume AWS Bucket Versioning Exists on R2

R2's S3 compatibility table is the source of truth, and it does not list bucket versioning. Both PutBucketVersioning and GetBucketVersioning are marked unimplemented. A design that depends on noncurrent versions is not portable to this endpoint, however familiar it is on AWS.

That removes the standard S3 recovery move. On AWS an overwrite leaves a noncurrent version, and a bad apply can be undone by copying it back. On R2 an overwrite replaces the object; the state you had ten seconds ago exists only where you put it.

Object Lock is not a substitute either. The bucket-level object-locking flag and the object-lock configuration calls are also unimplemented, so a write-once story does not transfer. Retention has to live in the snapshot store, not in the bucket.

Encryption is not history. R2 encrypts stored objects and keeps buckets private when you configure them that way, but neither property lets you read yesterday's bytes. Confidentiality and recoverability are different controls with different evidence.

A snapshot is a copy with an owner, a checksum and a restore path. A copy in the same bucket shares the failure domain, and a copy without a checksum cannot prove what was restored. Both gaps are easy to miss because the copy itself succeeds.

A same-bucket copy is a convenience, not a control. It is fast, cheap, and shares the credential, the lifecycle rules and the account with the original. Use it as a pre-change checkpoint; keep the durable copy where a bad policy cannot reach.

Plan snapshots on two clocks. A scheduled pull covers quiet drift; a manual pull before any risky change covers the known event. Store both outside the bucket that holds the live state, with a retention period longer than your slowest detection.

Name snapshots by time, not by intent. A file called before-fix.tfstate is unreadable six months later; a UTC timestamp plus the state serial is sortable and provable. Keep the checksum beside the name rather than inside the file, so the file itself stays byte-identical to what was pulled.

Use a separate credential for the copy. The apply credential writes one key; the snapshot credential reads it and writes somewhere else. That separation is what lets the recovery owner restore without borrowing the apply role.

Restoring backwards is a deliberate override. A snapshot carries a lower serial than the state it replaces, so writing it back needs force. That is the one place force belongs: a reviewed restore, with the current object copied aside first.

State contains secrets, so snapshots inherit the sensitivity. Private bucket, narrow token, access logging and a deletion date. A snapshot in a public bucket is a credential leak with a delay.

AWS S3 assumptionR2 statusReplacement control
Previous versions existBucket versioning unimplementedScheduled and pre-apply snapshots to a second location
An overwrite is reversibleWhole-object replacement, no historyRestore a checksummed snapshot, then plan
Object Lock blocks deletionObject-lock operations unimplementedSeparate account and bucket plus token scope
Lifecycle expires old versionsLifecycle applies to current objects onlyRetention enforced on the snapshot store

Verify the claim rather than the marketing. Ask the bucket for its versioning state and expect an error, or read the compatibility page for the current release and record the date. Compatibility pages change, and a feature that arrives later should change this design deliberately, not silently.

Migrate State with the Correct Init Semantics

Two flags with similar names produce opposite outcomes. -migrate-state copies existing state into the newly configured backend; -reconfigure discards the old backend configuration and copies nothing.

Use migration when the location changes. A new bucket, a new key or a move from another backend all qualify. Use reconfigure when only a credential, role or endpoint changed and the target already holds the state.

Reconfigure plus a changed key is the expensive mistake. Terraform initialises against empty state, sees no resources, and plans to create every object the configuration describes. Sometimes the provider rejects the duplicate name; sometimes it does not, and you own two copies.

The interactive prompt is the same decision. Init asks whether to copy existing state; answering no initialises the new backend empty. Automation replaces that prompt with a flag, so a wrong answer becomes a silent default instead of a visible one.

Take the snapshot before the flags. Pull state, record lineage and serial, and hash the file. Those fields are how you prove that the state which arrived is the state that left.

Migration reads and writes in one operation. The source must stay readable while init runs; revoking the old credential first turns a move into a restore. If the two backends cannot share a shell, pull first, reconfigure, then push.

Push has its own guard. A state file whose lineage differs from the destination is rejected, which is the behavior you want. Forcing past it is a decision for an incident, not a shortcut for a migration.

Saved plans do not survive the move. A plan file records the backend it was created against and the state serial it expects. Treat open plans as invalid after a migration and create a fresh one, or a correct move still ends in a rejected or misplaced apply.

Workspaces multiply the prompts. One init can migrate several workspace states, and each may ask separately. Automation that answers the first prompt and stops leaves part of the estate in the old location, which is why force-copy belongs in a reviewed pipeline rather than a shell history.

FlagWhat it doesUse whenFailure if misapplied
-migrate-stateCopies state into the new backendBucket, key or backend type changedSource unreadable, migration stops
-force-copyAnswers yes and implies migrationCI, after a verified snapshotWrong target copied without review
-reconfigureIgnores old config, copies nothingTarget already holds state; credential-only changeEmpty state, plan recreates everything
state pushWrites a pulled snapshotBackends cannot share credentialsLineage mismatch refuses, force overwrites

The widget pairs the backend shape with the sequence. The HCL carries no secret, and the shell assumes nothing about init being reversible.

terraform {
  required_version = "~> 1.17.1"

  required_providers {
    cloudflare = {
      source  = "cloudflare/cloudflare"
      version = "= 5.28.1"
    }
  }

  # The S3 backend is built into the CLI, not shipped by the provider.
  # Bucket, key and endpoint arrive at init time from a backend file.
  backend "s3" {}
}

# backends/r2.tfbackend -- values only, no secrets in version control
# bucket                      = "example-tfstate"
# key                         = "network/prod/terraform.tfstate"
# region                      = "auto"
# endpoints                   = { s3 = "https://<ACCOUNT_ID>.r2.cloudflarestorage.com" }
# use_lockfile                = true
# skip_credentials_validation = true
# skip_region_validation      = true
# skip_requesting_account_id  = true
# skip_s3_checksum            = true
# Pin the client: native S3 locking is not available on older releases.
terraform version

# 1. Snapshot before changing where state lives. This file contains secrets.
terraform state pull > "r2-backup-$(date -u +%Y%m%dT%H%M%SZ).tfstate"
shasum -a 256 r2-backup-*.tfstate   # sha256sum on Linux

# 2. Record what the snapshot claims, so the move can be proven (needs jq).
terraform state pull | jq -r '.lineage, .serial'

# 3. The key or bucket changed: copy the state into the R2 location.
terraform init -migrate-state -backend-config=backends/r2.tfbackend

# 4. Unattended CI, only after step 1 is confirmed.
terraform init -migrate-state -force-copy -backend-config=backends/r2.tfbackend

# 5. Verify ownership in the new location before any apply.
terraform state list
terraform plan

# 6. Fallback when the two backends cannot share credentials.
terraform state pull > carry.tfstate
terraform init -reconfigure -backend-config=backends/r2.tfbackend
terraform state push carry.tfstate

One command in that list is not a migration. Reconfigure appears only in the fallback, after a pull, and the push immediately restores the state. Running it alone against a new key is the failure the table describes.

Figure 4 shows the two outcomes side by side.

Migrate-state copies state to the new key while reconfigure leaves it behind The upper path shows a state object with a lineage and serial copied by init -migrate-state into the R2 backend under a new key, keeping the same lineage. The lower path shows reconfigure with a changed key producing empty state, after which a plan proposes to create every resource. The verification step is a state list and a plan that proposes no creates. Copy, ignore, or lose the state Old backend network/prod key lineage L, serial N source stays readable init -migrate-state R2 backend new key, same bucket same lineage L, serial N lock enabled at the endpoint Verify before apply state list matches addresses plan proposes no creates init -reconfigure, changed key old config ignored, nothing copied new location starts empty plan proposes to create everything duplicate names, or a second estate or reconfigure A backup without lineage and serial is a file, not evidence. A migration ends with a plan that proposes no creates, not with init reporting success.

A migration ends with a plan, not with an init message. The plan should read the expected lineage, list the same addresses and propose no creates. If it proposes to create what already exists, stop and restore; applying would adopt duplicates.

Demonstrate Lock Contention and Snapshot Restoration

A CI queue is a scheduling convention, not a lock. It orders the jobs that pass through it. It cannot see a manual apply, a run from another repository, or a runner replaced while still holding the object.

The failure is quiet at the end and loud in the middle. Two writers can both finish; the second overwrites the first's state, and the next plan reports drift for resources nobody changed. The lock error is the good outcome.

Contention can be missed by timing. A plan that finishes in two seconds and a second plan that starts a minute later never overlap, so a quiet run proves nothing. Hold the first operation open deliberately, or the test measures scheduling rather than locking.

Serial checks catch the quiet case. A successful overwrite leaves a higher serial and a plausible plan; only the record taken before the run shows that the earlier writer's changes vanished.

Reconciliation is the last step, not the first. After the contending runs, compare serial and lineage with the record, list addresses, confirm the lock object is gone, and read the remote objects the state claims. A clean plan against the wrong state is still wrong.

The lab below produces evidence you can attach to a review. It uses a provider-free scratch root, so the only moving parts are the CLI and the endpoint.

Write the verdict down. A compatibility note that says "tested" with no date, endpoint, CLI version or key is not reusable. Record all four, plus the two commands that produced the evidence.

Lab

Qualify an R2 backend

Status: lab, scratch account only. Two terminals, one scratch bucket, no production state. The output is a signed-off compatibility note, not a running backend.

Prerequisites. Terraform 1.17.1; an R2 access key limited to the scratch bucket; the account ID and endpoint in environment variables; curl and shasum on the machine. The root uses terraform_data, so no provider is installed.

Setup. Create the bucket with a dedicated prefix. Keep the state key outside any workload prefix, and keep every object in the bucket private.

#DoPass condition
1Create the scratch bucket and one prefix for the testNo public access; the state key is under labs/state/
2Init with the lockfile enabled against the test keyInit succeeds with no providers installed
3Terminal A: apply a terraform_data whose create runs a 120-second sleepThe lock object appears and A holds it
4Terminal B: plan with -lock-timeout=0s during the sleepB exits non-zero with a lock error naming A's operation
5Record the lock block, then check the lock object during and after APresent while A runs, absent when A finishes
6Snapshot to a file, copy it outside the bucket, change the resource, then push the snapshot back with -forcestate list matches the snapshot and the serial returns to the recorded value
7Reconcile the two writersSerial and lineage match the record; no lock object remains

Expected observation. Writer B is stopped by the backend, not by a queue, and the error names the path, operation, holder and creation time. The lock object disappears when A completes. The restored state carries the recorded serial, and the next plan proposes the change that was undone, which is how a restore proves itself.

Failure checks. The lab fails if B waits and then succeeds, because that is an unlocked backend. It fails if the snapshot lives only in the same bucket, because that is a copy rather than a recovery control. It fails if step 6 uses reconfigure with a changed key, because nothing was copied.

Cost and cleanup. Storage for a few small objects, billed until deleted. Destroy the scratch root, delete the test prefix, then the bucket; confirm both the state and lock objects are gone.

Evidence to keep. The lock error block, the two timestamps for the lock object, the snapshot checksum, the lineage and serial before and after, and the plan produced after the restore. Redact the account ID and key material.

Next in the Series

In Adopt Cloudflare Safely: Imports and Provider V4-to-V5 Migration, we'll explore Reconcile configuration and state migrations resource by resource while preserving actual service behavior.