Skip to main content

Infrastructure as code · Advanced · 24 min

Store the Relay state in S3 with locking and OpenTofu state encryption

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · OpenTofu 1.13.10 · hashicorp/aws 6.74

You will create a state bucket from a separate bootstrap configuration, move the Relay state into it with S3 locking, and encrypt that state and every saved plan with OpenTofu's own encryption, ready to switch to AWS KMS.

On this page

Relay now has a network and a web server, and everything OpenTofu knows about them sits in one file: ~/relay-demo/terraform.tfstate. That file is the only link between your code and what exists in AWS. It holds every resource ID, the instance's addresses, the IAM role's ARN and any attribute a provider chose to record, all as plain JSON. If your laptop is lost, the link is gone. If someone copies the file, they have a map of your account.

In this part you fix both problems. A small, separate bootstrap configuration creates a private, versioned S3 bucket for state. The Relay project moves its state into that bucket, with S3 locking so two runs cannot write at once. Then you turn on OpenTofu's own state encryption, which encrypts the state and every saved plan before they leave your machine, so a person who can read the bucket still cannot read the state.

This is different from S3 server-side encryption. S3 encrypts objects on its disks, but anyone allowed to GetObject receives the plain text. OpenTofu's encryption happens on the client, so the bucket only ever holds ciphertext. You will use both.

A note on cost: one bucket holding a few small versioned files is cheap, and step 8's KMS key has its own monthly and per-request charges. Check aws.amazon.com/s3/pricing/ and aws.amazon.com/kms/pricing/ for your Region before you start. Leave the bucket in place at the end: part 8 of the series removes it with everything else.

Step 1 · See what the local state gives away

Before you move anything, look at what you are protecting. Go to the project and list what the state tracks, then pull the resource types straight out of the file with grep:

Bash
cd ~/relay-demo
tofu state list
grep -o '"type": "[a-z0-9_]*"' terraform.tfstate | sort -u

grep needs no key, no AWS credentials and no OpenTofu. Neither does anyone who gets hold of the file. Open terraform.tfstate in an editor and search for arn: or private_ip to see how much more is there.

Check it worked

tofu state list prints addresses such as aws_s3_bucket.assets, aws_vpc.main, the subnets and security group rules from part 2 and the instance and IAM role from part 3. The grep prints the same resource types, such as "type": "aws_vpc", read directly from a file anyone can open.

Step 2 · Make a passphrase and keep it out of your history

OpenTofu's simplest key provider, pbkdf2, turns a passphrase into an encryption key. The passphrase must be at least 16 characters. Generate a random one into a file only you can read. The if stops you from overwriting a passphrase you already use, because a lost passphrase means state you can never read again:

Bash
mkdir -p -m 700 ~/.config/relay
if [ -s ~/.config/relay/state-passphrase ]; then
  echo "A passphrase already exists; keeping it."
else
  install -m 600 /dev/null ~/.config/relay/state-passphrase
  head -c 32 /dev/urandom | base64 > ~/.config/relay/state-passphrase
fi
export TF_VAR_state_passphrase="$(cat ~/.config/relay/state-passphrase)"

install -m 600 /dev/null creates the file private before anything is written to it. The last line hands the value to OpenTofu through an environment variable named TF_VAR_ plus the variable name, so it never appears on a command line or in a tfvars file that might reach Git. Run that export line in every new terminal before you use tofu in this project.

Now copy the contents of ~/.config/relay/state-passphrase into your password manager or your team's secret store. S3 versioning protects you against a bad write, but no old version helps if the key is gone.

Check it worked

ls -l ~/.config/relay/state-passphrase shows -rw-------, and echo ${#TF_VAR_state_passphrase} prints 44, the length of 32 random bytes in base64.

Step 3 · Create the state bucket from a bootstrap configuration

The bucket cannot be created by the Relay configuration that stores its state in it, since that configuration needs the bucket before it can run. Give it a configuration of its own in ~/relay-demo/bootstrap. It keeps its own small state locally, encrypted from the first apply.

Bash
mkdir -p ~/relay-demo/bootstrap
cd ~/relay-demo/bootstrap
cat > main.tf <<'HCL'
terraform {
  required_version = ">= 1.13.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 6.74"
    }
  }

  encryption {
    key_provider "pbkdf2" "bootstrap" {
      passphrase = var.state_passphrase
    }

    method "aes_gcm" "bootstrap" {
      keys = key_provider.pbkdf2.bootstrap
    }

    state {
      method   = method.aes_gcm.bootstrap
      enforced = true
    }

    plan {
      method   = method.aes_gcm.bootstrap
      enforced = true
    }
  }
}

variable "state_passphrase" {
  type        = string
  description = "State and plan encryption passphrase. Set TF_VAR_state_passphrase."
  sensitive   = true
}

variable "aws_region" {
  type    = string
  default = "eu-west-1"
}

provider "aws" {
  region = var.aws_region

  default_tags {
    tags = {
      Project   = "relay"
      ManagedBy = "opentofu-bootstrap"
    }
  }
}

data "aws_caller_identity" "current" {}

resource "aws_s3_bucket" "state" {
  bucket = "relay-tfstate-${data.aws_caller_identity.current.account_id}-${var.aws_region}"
}

resource "aws_s3_bucket_versioning" "state" {
  bucket = aws_s3_bucket.state.id

  versioning_configuration {
    status = "Enabled"
  }
}

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
}

resource "aws_s3_bucket_server_side_encryption_configuration" "state" {
  bucket = aws_s3_bucket.state.id

  rule {
    apply_server_side_encryption_by_default {
      sse_algorithm = "AES256"
    }
  }
}

data "aws_iam_policy_document" "tls_only" {
  statement {
    sid     = "DenyInsecureTransport"
    effect  = "Deny"
    actions = ["s3:*"]
    resources = [
      aws_s3_bucket.state.arn,
      "${aws_s3_bucket.state.arn}/*",
    ]

    principals {
      type        = "*"
      identifiers = ["*"]
    }

    condition {
      test     = "Bool"
      variable = "aws:SecureTransport"
      values   = ["false"]
    }
  }
}

resource "aws_s3_bucket_policy" "state" {
  bucket = aws_s3_bucket.state.id
  policy = data.aws_iam_policy_document.tls_only.json

  depends_on = [aws_s3_bucket_public_access_block.state]
}

output "state_bucket" {
  value = aws_s3_bucket.state.bucket
}

output "region" {
  value = var.aws_region
}
HCL

What each part is for:

  • The bucket name includes your account number and Region, because S3 bucket names are global across all of AWS.
  • Versioning keeps every earlier copy of the state, so a bad write can be rolled back.
  • The public access block and the bucket policy make sure nothing reaches the bucket anonymously or over plain HTTP.
  • Default encryption with S3-managed keys covers anything written to the bucket. OpenTofu's encryption is a second layer on top.
  • The encryption block appears here with enforced = true from the start. This is a new state, so there is nothing to migrate.

Keep aws_region the same as Relay's. If you deploy Relay to an opt-in Region such as af-south-1 (Cape Town), put the state bucket there too, so the state stays close to the resources and within the same data rules.

Initialise, plan to a file and apply that plan:

Bash
tofu init
tofu fmt -check
tofu validate
tofu plan -out=bootstrap.tfplan
tofu apply bootstrap.tfplan
rm bootstrap.tfplan

This folder downloads its own copy of the AWS provider: about 174 MB as a zip for 6.74.0 on linux_amd64. If you pay for data by the gigabyte, as many people on prepaid bundles do, set TF_PLUGIN_CACHE_DIR to a folder such as ~/.terraform.d/plugin-cache (create it first) in your shell profile, and later projects reuse the download instead of fetching it again.

Keep the bucket name and Region for the next steps:

Bash
BUCKET=$(tofu output -raw state_bucket)
REGION=$(tofu output -raw region)
echo "$BUCKET in $REGION"
aws s3api get-bucket-versioning --bucket "$BUCKET"
grep -oE '"(meta|encrypted_data|encryption_version)"' terraform.tfstate

Check it worked

The apply ends with Apply complete! Resources: 5 added, 0 changed, 0 destroyed. The echo prints something like relay-tfstate-123456789012-eu-west-1 in eu-west-1, with your account number. get-bucket-versioning shows "Status": "Enabled". The last grep finds "meta", "encrypted_data" and "encryption_version" in the bootstrap state, and nothing readable about the bucket: that file is already ciphertext. Back up bootstrap/terraform.tfstate with your passphrase; you only need it again to change or delete the bucket.

Step 4 · Point Relay at the bucket and add encryption

Go back to the Relay project. Write the backend from the two values you saved, so there is nothing to type by hand. The unquoted HCL marker lets the shell fill in $BUCKET and $REGION:

Bash
cd ~/relay-demo
cat > backend.tf <<HCL
terraform {
  backend "s3" {
    bucket       = "${BUCKET}"
    key          = "relay/dev/terraform.tfstate"
    region       = "${REGION}"
    encrypt      = true
    use_lockfile = true
  }
}
HCL
cat backend.tf
  • key is the object path of this state inside the bucket. A production copy of Relay would get its own key, such as relay/prod/terraform.tfstate, so the two can never overwrite each other.
  • encrypt = true asks S3 for server-side encryption on every write.
  • use_lockfile = true turns on locking in the bucket itself. At the start of each run OpenTofu writes a lock object next to the state, named after the key with .tflock added, using a conditional write that fails if the object already exists. A second run sees the lock and stops instead of overwriting the first one's work. No DynamoDB table is needed.

Now add the encryption settings in their own file. They have one extra method, unencrypted, used as a fallback so OpenTofu can still read today's plain-text state while it writes the new, encrypted one:

Bash
cat > encryption.tf <<'HCL'
variable "state_passphrase" {
  type        = string
  description = "State and plan encryption passphrase. Set TF_VAR_state_passphrase; never put it in a tfvars file."
  sensitive   = true
}

terraform {
  encryption {
    key_provider "pbkdf2" "relay" {
      passphrase = var.state_passphrase
    }

    method "aes_gcm" "relay" {
      keys = key_provider.pbkdf2.relay
    }

    # Only for reading the old plain-text state. Removed in step 6.
    method "unencrypted" "migrate" {}

    state {
      method = method.aes_gcm.relay

      fallback {
        method = method.unencrypted.migrate
      }
    }

    plan {
      method   = method.aes_gcm.relay
      enforced = true
    }
  }
}
HCL
tofu fmt -check

The names relay on the key provider and the method are stored with the encrypted data. Do not rename them once the state is encrypted, or OpenTofu cannot find the key to read it.

Check it worked

cat backend.tf shows your real bucket name and Region, not ${BUCKET}. tofu fmt -check prints nothing and exits without an error, which means both new files are already in the standard layout.

Step 5 · Move the state into the bucket

tofu init sees that the backend has changed. With -migrate-state it copies the existing state to S3, and because the encryption block is in place, the copy is written encrypted:

Bash
tofu init -migrate-state

When it asks whether to copy the existing state to the new backend, answer yes.

Check that the state arrived, then download the object and confirm it is ciphertext. The if fails loudly if a resource type can still be read from the file:

Bash
tofu state list
aws s3 ls "s3://${BUCKET}/relay/dev/"
aws s3 cp "s3://${BUCKET}/relay/dev/terraform.tfstate" state-from-s3.json
grep -oE '"(meta|encrypted_data|encryption_version)"' state-from-s3.json
if grep -q '"aws_vpc"' state-from-s3.json; then
  echo "The state in S3 is readable: check encryption.tf before going on."
  false
fi
rm state-from-s3.json
tofu plan -var-file=dev.tfvars

The old local terraform.tfstate, and any terraform.tfstate.backup next to it, are now out of date and still plain text. Warning: the next command deletes them. Run it only after the checks above pass, because until then the local file is your only good copy.

Bash
rm -f terraform.tfstate terraform.tfstate.backup

Check it worked

tofu state list prints the same addresses as in step 1, now read from S3 and decrypted with your passphrase. The bucket listing shows one object, terraform.tfstate, and no .tflock, because OpenTofu deletes the lock when a run ends. The downloaded copy contains "meta", "encrypted_data" and "encryption_version" and no resource types. The plan ends with No changes. Your infrastructure matches the configuration. If a run is ever killed and leaves a lock behind, OpenTofu prints the lock ID; clear it with tofu force-unlock <lock-id> only once you are sure no other run is active.

Step 6 · Enforce encryption and encrypt saved plans

The fallback was only for the move. Left in place, it would let OpenTofu accept a plain-text state that someone uploads to the bucket. Rewrite encryption.tf without it, and with enforced = true so OpenTofu refuses to write state unencrypted:

Bash
cat > encryption.tf <<'HCL'
variable "state_passphrase" {
  type        = string
  description = "State and plan encryption passphrase. Set TF_VAR_state_passphrase; never put it in a tfvars file."
  sensitive   = true
}

terraform {
  encryption {
    key_provider "pbkdf2" "relay" {
      passphrase = var.state_passphrase
    }

    method "aes_gcm" "relay" {
      keys = key_provider.pbkdf2.relay
    }

    state {
      method   = method.aes_gcm.relay
      enforced = true
    }

    plan {
      method   = method.aes_gcm.relay
      enforced = true
    }
  }
}
HCL

Saved plans matter as much as state. A plan file holds the values OpenTofu is about to write, sensitive ones included. The plan block has been encrypting them since the last step. Save one and read it back:

Bash
tofu plan -var-file=dev.tfvars -out=relay.tfplan
tofu show relay.tfplan

Check it worked

The plan still reports No changes., which shows OpenTofu read the encrypted state without the fallback. tofu show relay.tfplan prints the plan. Keep relay.tfplan for the next step. Part 1's .gitignore already lists *.tfplan next to *.tfstate, so saved plans stay out of Git.

Step 7 · See what a wrong passphrase does

Try to read the state and the plan with a different passphrase. It is 16 characters or longer on purpose: a shorter one fails earlier, with a passphrase is too short configuration error, which proves nothing.

Bash
if TF_VAR_state_passphrase='this-is-not-the-relay-passphrase' tofu state list > wrong-key.txt 2>&1; then
  echo "The state opened with the wrong passphrase."
  false
fi
cat wrong-key.txt
if TF_VAR_state_passphrase='this-is-not-the-relay-passphrase' tofu show relay.tfplan > wrong-key-plan.txt 2>&1; then
  echo "The plan opened with the wrong passphrase."
  false
fi
rm relay.tfplan

Both commands fail, and neither changes anything in S3: reading never writes. That is also what happens to a CI job or a teammate who has the bucket permissions but not the key.

To change the passphrase later, use the same fallback idea as the migration. Add a second key provider and method for the new passphrase, make it the primary method, and move the old one into fallback. Run tofu apply -var-file=dev.tfvars so the state is written with the new key, check it, then remove the old provider:

HCL
key_provider "pbkdf2" "relay_2027" {
  passphrase = var.state_passphrase_2027
}

method "aes_gcm" "relay_2027" {
  keys = key_provider.pbkdf2.relay_2027
}

state {
  method   = method.aes_gcm.relay_2027
  enforced = true

  fallback {
    method = method.aes_gcm.relay
  }
}

Check it worked

cat wrong-key.txt shows an error that includes decryption failed for all provided methods, followed by the reason for each method it tried. The plan check fails the same way. With your own passphrase exported, tofu state list still works.

Step 8 · Move to an AWS KMS key for production

A passphrase is a shared secret that people copy around. For production, let AWS KMS hold the key instead. OpenTofu's aws_kms key provider asks KMS for a fresh data key for each state or plan file and stores that data key, encrypted by KMS, next to the ciphertext. Access then comes down to IAM: whoever may call kms:GenerateDataKey and kms:Decrypt on the key can run OpenTofu, and you can revoke that without changing a secret. It also means CI can authenticate with a role, which suits the CI pipeline in part 7.

A customer managed KMS key bills every month it exists, plus per request; check aws.amazon.com/kms/pricing/ for your Region before you create one. Create a key and turn on automatic rotation, replacing <key-id> with the ID the first command prints:

Bash
aws kms create-key --description "Relay OpenTofu state" --query KeyMetadata.KeyId --output text
aws kms enable-key-rotation --key-id <key-id>

Then add a KMS key provider and method to encryption.tf, make them primary, and keep the passphrase method as the fallback until the state has been rewritten. The terraform { encryption { ... } } part now reads like this, with your own key ARN and Region in place of the example values:

HCL
key_provider "pbkdf2" "relay" {
  passphrase = var.state_passphrase
}

method "aes_gcm" "relay" {
  keys = key_provider.pbkdf2.relay
}

key_provider "aws_kms" "relay_kms" {
  kms_key_id = "arn:aws:kms:eu-west-1:123456789012:key/replace-with-your-key-id"
  region     = "eu-west-1"
  key_spec   = "AES_256"
}

method "aes_gcm" "relay_kms" {
  keys = key_provider.aws_kms.relay_kms
}

state {
  method   = method.aes_gcm.relay_kms
  enforced = true

  fallback {
    method = method.aes_gcm.relay
  }
}

plan {
  method   = method.aes_gcm.relay_kms
  enforced = true
}

key_spec = "AES_256" asks KMS for a 32-byte data key, which is what aes_gcm needs. The key provider signs in to AWS the same way as the S3 backend, so your existing credentials or role are used. Run tofu apply -var-file=dev.tfvars to write the state with the KMS method. Once it is rewritten, delete the pbkdf2 provider, its method, the fallback and the state_passphrase variable.

Check it worked

Download the state object again as in step 5. Its meta section now refers to the KMS key provider, with a name something like key_provider.aws_kms.relay_kms, instead of the pbkdf2 one. tofu state list works with TF_VAR_state_passphrase unset, and fails for a role without kms:Decrypt on the key. Leave the bucket and its contents in place for the rest of the series.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.