This is a .tfstate backend running as a Cloudflare worker, storing the
state in a R2 bucket. It supports locking.
To use this backend, you'll need to deploy the worker to the Cloudflare account where the bucket is located.
Create the R2 bucket if it does not already exist.
npx wrangler r2 bucket create <NAME>Generate a secure shared key, using a command like below:
pwgen --symbols --secure 512 1Create the secret (the worker expects the name psk, Wrangler
will prompt you to enter the secret value):
npx wrangler secret put pskCopy the wrangler.toml.example file to wrangler.toml, then modify
it to suit your environment.
See https://developers.cloudflare.com/workers/wrangler/configuration/ for more details on the configuration settings.
Run npx wrangler deploy to deploy it to Cloudflare.
You can verify that it has worked by calling https://<YOUR_HOST>/health,
if it worked, and the secret psk was present, you will see the string
UP as the response.
To use this backend in Terraform, you need to use the http backend, as follows,
where <YOUR_HOST> is the host your worker is deployed at, and <NAME> is
a name for the Terraform state file (without the .tfstate suffix).
The user name can be anything, it will be ignored.
The password should be the value of the psk secret created above.
Of course, don't store it in your Terraform file, but pass it in via
e.g. -backend-config=password=<PSK> when doing init,
having read the PSK value from a secure secret store.
backend "http" {
address = "https://<YOUR_HOST>/state/<NAME>"
lock_address = "https://<YOUR_HOST>/state/<NAME>/lock"
lock_method = "PUT"
unlock_address = "https://<YOUR_HOST>/state/<NAME>/lock"
unlock_method = "DELETE"
username = "terraform"
password = "<PSK>"
}The blog post Implementing a Terraform state backend on Cloudflare workers was super useful, and I basically cribbed the approach, but implemented the worker myself as a pet project.