INF-2Required
Keep state remote with locking and encryption
Keep the state file in a remote backend that locks, encrypts and keeps old versions. Only the deploy roles may read it. Never keep state in git or on a laptop.
How to do it
The state file holds every attribute of every resource in plain text, sometimes with passwords. Store it in a bucket with versioning, encryption and public access blocked. In the S3 backend, set use_lockfile = true. It needs Terraform 1.11 or OpenTofu 1.10 or later, and Terraform has deprecated the older DynamoDB lock table, while OpenTofu still supports it. OpenTofu can also encrypt state and plan files on the client with its encryption block and a key from a key service. Set enforced = true, so an unencrypted file is refused. Pulumi encrypts secret values in state with a secrets provider. State can hold secrets, so the reasons in Keep secrets out of code apply to it too.
Examples
Terraform example
terraform {
backend "s3" {
bucket = "example-shop-state"
key = "production/network.tfstate"
region = "eu-north-1"
encrypt = true
use_lockfile = true
}
}
Terraform example 2
# OpenTofu only: state and plan files are encrypted before they leave the runner
terraform {
encryption {
key_provider "aws_kms" "state" {
kms_key_id = "alias/example-shop-state"
region = "eu-north-1"
key_spec = "AES_256"
}
method "aes_gcm" "state" {
keys = key_provider.aws_kms.state
}
state {
method = method.aes_gcm.state
enforced = true
}
plan {
method = method.aes_gcm.state
enforced = true
}
}
}
Shell example
aws s3api get-bucket-versioning --bucket example-shop-state # "Status": "Enabled"
aws s3api get-public-access-block --bucket example-shop-state # all four settings true
How to check
git ls-files '*.tfstate*' prints nothing. Start two plans on the same state at once, and the second stops with a lock error. The bucket reports versioning Enabled and public access blocked. Its policy grants read access to the deploy roles only.
Sources
Related rules
- APS-60 Keep secrets out of code in Application security
- INF-24 Keep secrets out of state in Infrastructure and environments
- STK-54 Use OpenTofu for infrastructure as code in Software choices
For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/infrastructure/infrastructure-as-code/remote-state">Agent Wranglers infrastructure and environments playbook</a>. In code you write, add a comment next to it with the same link.