Infrastructure as code · Advanced · 24 min
Keep secrets out of Terraform state with ephemeral values and write-only arguments
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Terraform 1.17.2 · hashicorp/aws 6.74 · hashicorp/random 3.9
You will find a password sitting in plain text in a Terraform state file, then rebuild the same setup with ephemeral values, write-only arguments and a secret read from AWS Secrets Manager at apply time, and prove with grep that the state no longer holds it.
On this page
Terraform's state file is a full record of every resource it manages, and that record includes the arguments you passed in. If you set a database password in a resource, the password is in terraform.tfstate. Marking it sensitive = true changes what Terraform prints on screen. It does not change what Terraform writes to disk, and anyone who can read the state, or an old copy of it, can read the password.
Terraform 1.10 and 1.11 added the tools to fix this properly. An ephemeral value exists only while one terraform command runs and is never written to state or to a plan file. A write-only argument is a resource argument, usually ending in _wo, that accepts such a value, sends it to the provider and stores null in its place. Because Terraform keeps no copy, you tell it when to send a new value with a version number next to the argument.
In this tutorial you first see the leak with your own eyes, then remove it step by step: an ephemeral variable and an ephemeral password on your machine, a password stored in AWS Secrets Manager through a write-only argument, and a PostgreSQL database on RDS whose master password is read from Secrets Manager at apply time. After each change you search the state for the secret. OpenTofu 1.11 added the same features under the same names, so the steps should also work in OpenTofu 1.11 and later, including the current 1.13 release (not run for this tutorial); replace terraform with tofu in the commands.
Step 1 · Install Terraform 1.17.2
Terraform is published as a zip archive with a SHA-256 checksum list on releases.hashicorp.com. Install the tools to fetch and unpack it, then download both files. dpkg --print-architecture prints amd64 or arm64, which matches HashiCorp's file names:
sudo apt update
sudo apt install -y curl unzip ca-certificates
VERSION=1.17.2
ARCH=$(dpkg --print-architecture)
cd "$(mktemp -d)"
curl -fsSLO "https://releases.hashicorp.com/terraform/${VERSION}/terraform_${VERSION}_linux_${ARCH}.zip"
curl -fsSLO "https://releases.hashicorp.com/terraform/${VERSION}/terraform_${VERSION}_SHA256SUMS"
sha256sum --ignore-missing -c "terraform_${VERSION}_SHA256SUMS"The last line must say terraform_1.17.2_linux_<arch>.zip: OK. If it says FAILED, download again before going on. Then install the binary:
unzip -o -q "terraform_${VERSION}_linux_${ARCH}.zip" terraform
sudo install -m 0755 terraform /usr/local/bin/terraform
terraform versionA binary installed this way gets no updates from apt. To upgrade, repeat this step with the new version number. HashiCorp also runs an apt repository if you would rather have upgrades through apt.
You will run terraform init in three folders, and two of them download the AWS provider, which is a large file. A plugin cache makes Terraform download each provider once and reuse it, which helps on metered or prepaid mobile data:
mkdir -p ~/.terraform.d/plugin-cache
export TF_PLUGIN_CACHE_DIR="$HOME/.terraform.d/plugin-cache"Add the export line to ~/.bashrc if you want it in every new shell.
Check it worked
terraform version prints Terraform v1.17.2 and your platform, such as on linux_amd64.
Step 2 · Find a sensitive password in plain text
Make a throwaway folder and write a configuration that generates a database password the usual way, as a managed resource, and outputs it with sensitive = true:
mkdir -p ~/tf-secrets-demo/local
cd ~/tf-secrets-demo/local
cat > main.tf <<'HCL'
terraform {
required_version = ">= 1.11.0"
required_providers {
random = {
source = "hashicorp/random"
version = "~> 3.9"
}
}
}
resource "random_password" "db" {
length = 24
override_special = "-_.:"
}
output "db_password" {
value = random_password.db.result
sensitive = true
}
HCL
terraform init
terraform plan -out=tfplan
terraform apply tfplanoverride_special limits the symbols to four that never need escaping in JSON. That matters because Terraform's JSON encoder writes <, > and & as \u003c, \u003e and \u0026, so with those symbols in the password the state file would hold \u003c in place of < and a plain text search for the real password could miss it.
Now look at what Terraform shows, and then at what it saved:
terraform output
terraform output -raw db_password; echo
grep -n '"result"' terraform.tfstateCheck it worked
terraform output prints db_password = <sensitive>. The next command prints the password itself, because -raw and -json show sensitive values in full. The grep prints a line such as "result": "mK3-v..." with the same 24 characters. The value is in the state in plain text, and in every copy of that state: backups, old versions in a versioned bucket, and a laptop that once ran terraform state pull.
Step 3 · Replace it with an ephemeral password and variable
Rewrite main.tf. The random_password becomes an ephemeral block, which generates a fresh value on each run and keeps it in memory only. A new variable, api_token, is marked ephemeral = true, so Terraform refuses to store it either. Both values go to a one-off setup script through a provisioner, one of the few places where ephemeral values are allowed. The others are locals, write-only arguments, provider blocks, other ephemeral blocks and outputs of child modules marked ephemeral. A root module output cannot hold an ephemeral value, so there is no way to print this one by accident.
cat > main.tf <<'HCL'
terraform {
required_version = ">= 1.11.0"
required_providers {
random = {
source = "hashicorp/random"
version = "~> 3.9"
}
}
}
variable "api_token" {
type = string
description = "Token for the one-off setup script. Supply it with TF_VAR_api_token."
ephemeral = true
sensitive = true
}
ephemeral "random_password" "db" {
length = 24
override_special = "-_.:"
}
resource "terraform_data" "handoff" {
provisioner "local-exec" {
command = "sh ./handoff.sh"
environment = {
DB_PASSWORD = ephemeral.random_password.db.result
API_TOKEN = var.api_token
}
}
}
HCL
cat > handoff.sh <<'SH'
#!/bin/sh
# Stands in for a script that sets a password on another system.
set -eu
[ "${#DB_PASSWORD}" -eq 24 ]
[ -n "$API_TOKEN" ]
echo "handoff ok: received a ${#DB_PASSWORD}-character password and a token" > handoff.txt
SHSupply the token through an environment variable. read -rs prompts without echoing, so the value stays out of your shell history and the process list. Type any string for this exercise:
read -rs -p "API token: " TF_VAR_api_token; echo
export TF_VAR_api_tokenPlan and apply. The plan removes the old random_password resource and its output, and creates terraform_data.handoff. You will also see lines such as ephemeral.random_password.db: Opening... and Closing...: Terraform opens the ephemeral resource for the run and throws the value away afterwards.
terraform plan -out=tfplan
terraform apply tfplan
cat handoff.txt
terraform state listA saved plan holds no ephemeral values either, so TF_VAR_api_token must still be set when you run terraform apply tfplan, as it is here.
Search the new state for the token and for any stored password:
if printf '%s\n' "$TF_VAR_api_token" | grep -qFf - terraform.tfstate; then echo "LEAK: the token is in the state"; false; else echo "token not in state"; fi
grep -c '"result"' terraform.tfstate || echo "no password in state"The old password has not quite gone. Terraform writes the previous state to terraform.tfstate.backup on each apply, and that copy still has it:
grep -c '"result"' terraform.tfstate.backup
rm terraform.tfstate.backupCheck it worked
handoff.txt says handoff ok: received a 24-character password and a token, so the script got both values. terraform state list shows only terraform_data.handoff. The two searches print token not in state and then 0 followed by no password in state. The backup search printed 1 before you deleted the file. With a remote backend the same lesson applies to the old versions the backend keeps, which you deal with in the last step.
Step 4 · Store a generated password in Secrets Manager with a write-only argument
A real password has to live somewhere other than the state. In this step Terraform generates one and writes it into AWS Secrets Manager through secret_string_wo, the write-only form of secret_string. Next to it, secret_string_wo_version is an ordinary number that Terraform does store. Terraform sends a new secret value only when that number changes.
Check that the AWS CLI can reach your sandbox account. It prints your account ID and the identity you are using:
aws sts get-caller-identitySecrets Manager charges per secret per month and per API call, so the secret you create here bills until you delete it in the last step. See the Secrets Manager pricing page for current rates. The region is a variable; af-south-1 (Cape Town) works too, but it is an opt-in region that must be enabled in your account first.
Create the folder and the configuration. The secret is created with recovery_window_in_days = 0, which deletes it at once on destroy instead of keeping it for a recovery period. That suits a throwaway secret, never a production one.
mkdir -p ~/tf-secrets-demo/vault
cd ~/tf-secrets-demo/vault
cat > main.tf <<'HCL'
terraform {
required_version = ">= 1.11.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 6.74"
}
random = {
source = "hashicorp/random"
version = "~> 3.9"
}
}
}
variable "region" {
type = string
default = "eu-west-1"
}
variable "password_version" {
type = number
description = "Raise by one to generate and store a new password."
default = 1
}
provider "aws" {
region = var.region
}
ephemeral "random_password" "db" {
length = 32
override_special = "-_.:"
}
resource "aws_secretsmanager_secret" "db" {
name = "tf-secrets-demo/db-master"
description = "Master password for the tf-secrets-demo database"
recovery_window_in_days = 0
}
resource "aws_secretsmanager_secret_version" "db" {
secret_id = aws_secretsmanager_secret.db.id
secret_string_wo = ephemeral.random_password.db.result
secret_string_wo_version = var.password_version
}
HCL
terraform init
terraform plan -out=tfplan
terraform apply tfplanIn the plan, secret_string_wo shows as (write-only attribute) rather than a value. Confirm that the secret arrived without printing it, then search the state for it:
aws secretsmanager get-secret-value --secret-id tf-secrets-demo/db-master --query 'length(SecretString)'
PW=$(aws secretsmanager get-secret-value --secret-id tf-secrets-demo/db-master --query SecretString --output text)
if printf '%s\n' "$PW" | grep -qFf - terraform.tfstate; then echo "LEAK: the password is in the state"; false; else echo "password not in state"; fi
unset PW
grep -E '"secret_string_wo(_version)?"' terraform.tfstateCheck it worked
The first command prints 32, the length of the stored password. The search prints password not in state. The last grep shows something like "secret_string_wo": null and "secret_string_wo_version": 1: Terraform recorded that a value was sent and which version it was, but not the value.
Step 5 · Read the secret at apply time for an RDS database
The database lives in its own folder, as it would if a different team owned it. It does not generate or store the password. It looks the secret up by name, reads the current value with an ephemeral aws_secretsmanager_secret_version, and hands it to password_wo, the write-only form of aws_db_instance's password. The data source in the file reads only the secret's metadata, such as its ARN, so it is safe to keep in state.
An RDS instance bills by the hour from the moment it exists, including storage, until you destroy it in the last step. db.t4g.micro is one of the smallest classes; check the RDS for PostgreSQL pricing page for your region. The instance goes into your account's default VPC and is not publicly reachable. Creating it on AWS takes several minutes.
mkdir -p ~/tf-secrets-demo/db
cd ~/tf-secrets-demo/db
cat > main.tf <<'HCL'
terraform {
required_version = ">= 1.11.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 6.74"
}
}
}
variable "region" {
type = string
default = "eu-west-1"
}
variable "password_version" {
type = number
description = "Raise by one after the secret changes, to send the new password to RDS."
default = 1
}
provider "aws" {
region = var.region
}
data "aws_secretsmanager_secret" "db" {
name = "tf-secrets-demo/db-master"
}
ephemeral "aws_secretsmanager_secret_version" "db" {
secret_id = data.aws_secretsmanager_secret.db.id
}
resource "aws_db_instance" "app" {
identifier = "tf-secrets-demo"
engine = "postgres"
instance_class = "db.t4g.micro"
allocated_storage = 20
username = "app_admin"
password_wo = ephemeral.aws_secretsmanager_secret_version.db.secret_string
password_wo_version = var.password_version
publicly_accessible = false
skip_final_snapshot = true
}
HCL
terraform init
terraform plan -out=tfplan
terraform apply tfplanskip_final_snapshot = true means destroy deletes the database without a backup. Leave it out for any database whose data you care about.
Search the state for the password the database received:
PW=$(aws secretsmanager get-secret-value --secret-id tf-secrets-demo/db-master --query SecretString --output text)
if printf '%s\n' "$PW" | grep -qFf - terraform.tfstate; then echo "LEAK: the password is in the state"; false; else echo "password not in state"; fi
unset PW
grep -E '"password(_wo|_wo_version)?"' terraform.tfstateIf you do not need Terraform to handle the password at all, RDS can generate and rotate it for you in Secrets Manager: set manage_master_user_password = true instead of password_wo. The pattern in this step is for when you need the password under your own control, for example because an application reads the same secret.
Check it worked
The search prints password not in state, and the last grep shows something like "password": null, "password_wo": null and "password_wo_version": 1. aws rds describe-db-instances --db-instance-identifier tf-secrets-demo --query 'DBInstances[0].DBInstanceStatus' prints "available", because terraform apply waits for the database to be ready before it finishes.
Step 6 · Rotate the password with the version numbers
Terraform cannot tell that a write-only value changed, because it never kept the old one. The version numbers are how you tell it. Rotate in two moves: store a new password, then send it to the database. Between the two, the database still has the old password while the secret holds the new one, so applications that read the secret fail to connect until the second apply. Do this in a quiet period, or use a rotation scheme with two users if you cannot accept the gap.
Record a fingerprint of the current secret, then raise its version and apply. The version sits in terraform.tfvars, which Terraform reads automatically, so it is kept for the next run:
cd ~/tf-secrets-demo/vault
BEFORE=$(aws secretsmanager get-secret-value --secret-id tf-secrets-demo/db-master --query SecretString --output text | sha256sum)
echo 'password_version = 2' > terraform.tfvars
terraform plan -out=tfplan
terraform apply tfplan
AFTER=$(aws secretsmanager get-secret-value --secret-id tf-secrets-demo/db-master --query SecretString --output text | sha256sum)
if [ "$BEFORE" != "$AFTER" ]; then echo "secret changed"; else echo "secret did not change"; false; fiThe plan shows the change as secret_string_wo_version going from 1 to 2. Now send the new value to the database the same way:
cd ~/tf-secrets-demo/db
echo 'password_version = 2' > terraform.tfvars
terraform plan -out=tfplan
terraform apply tfplan
PW=$(aws secretsmanager get-secret-value --secret-id tf-secrets-demo/db-master --query SecretString --output text)
if printf '%s\n' "$PW" | grep -qFf - terraform.tfstate; then echo "LEAK: the password is in the state"; false; else echo "password not in state"; fi
unset PWCheck it worked
The first block prints secret changed. The database plan shows password_wo_version going from 1 to 2 as an in-place update, not a replacement; if a plan ever says the database must be replaced, stop and read why before you apply. The final search prints password not in state.
Step 7 · Clean up and lock down what is left
Destroy the database first, because its configuration reads the secret and fails if the secret has already gone. Read each list before you type yes:
cd ~/tf-secrets-demo/db
terraform destroy
cd ~/tf-secrets-demo/vault
terraform destroyThen confirm nothing is left in AWS and remove the local files, including the plan files and state backups:
aws secretsmanager list-secrets --query "SecretList[?starts_with(Name, 'tf-secrets-demo')].Name"
aws rds describe-db-instances --query "DBInstances[?DBInstanceIdentifier=='tf-secrets-demo'].DBInstanceStatus"
cd ~
rm -rf ~/tf-secrets-demo
unset TF_VAR_api_tokenThe provider cache in ~/.terraform.d/plugin-cache still holds the large AWS provider download from the first step. Keep it if you plan to do more Terraform tutorials; otherwise remove it, and delete the export TF_PLUGIN_CACHE_DIR=... line from ~/.bashrc if you added it:
rm -rf ~/.terraform.d/plugin-cache
unset TF_PLUGIN_CACHE_DIREphemeral values and write-only arguments shrink what the state holds, but the state still describes your whole system: hostnames, ARNs, user names, and secrets in any resource whose provider has no write-only argument yet. Treat it as sensitive regardless:
- Encrypt state at rest. On S3, turn on encryption for the bucket and the backend, ideally with a KMS key whose use you can audit. OpenTofu can also encrypt the state before it leaves your machine, which the remote state tutorial below sets up.
- Restrict who can read it. Reading state is reading secrets. Give read access to the state bucket or workspace only to the people and pipelines that run Terraform, and keep it separate from read access to the code.
- Remember the old copies. Versioned buckets keep every earlier state, including ones from before you moved to write-only arguments. After a migration, rotate any password that was ever in the state, then expire the old versions.
- Never output secrets.
sensitive = truehides an output on screen only;terraform output -rawand-jsonprint it, and the state holds it. If another configuration needs a secret, have it read the secret from the secrets manager with an ephemeral resource, as the database did here. - Prefer write-only and ephemeral forms. Before you write
password =in a resource, check the provider's documentation for a_woargument or an ephemeral resource.
Check it worked
Both AWS queries print []: no secret named tf-secrets-demo... and no database called tf-secrets-demo remain. In the AWS console, the Secrets Manager and RDS pages for your region show neither. ls ~/tf-secrets-demo reports that the folder does not exist.
Next steps
- Keep the state itself safe with remote state and encryption, which adds OpenTofu's client-side state encryption.
- Reject unsafe inputs before they reach a plan with validation, preconditions and check blocks.
- Stop secrets reaching your repository in the first place with keep secrets out of Git.
Related tutorials
- Turn the Relay network into a reusable OpenTofu moduleYou will move Relay's VPC, subnets, routes and web security group into a local modules/network module with its own inputs, outputs and README, and adopt the 18 running objects with moved blocks so the plan destroys nothing.
- Test the Relay network module with tofu test and mock providersYou will have a tofu test suite for Relay's network module that checks subnet ranges, input validation and outputs against a mocked AWS provider, and passes in seconds with no credentials.
- Store the Relay state in S3 with locking and OpenTofu state encryptionYou 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.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials