Full lesson
Explore the full explanation, examples, and visuals at your own pace.
variables.tf
Setting sensitive equals true doesn't hide your password in state. It only redacts what plan and apply print, so the terminal shows sensitive value. But the real db_password still gets recorded in terraform.tfstate, and that file is where the leak happens.
variable "db_password" {
type = string
sensitive = true
}
# terraform plan shows:
# + password = (sensitive value)Step 1: what the terminal sees
Follow the value. The db_password variable is passed into terraform apply, and what it carries is the real S3cr3t!. Terraform needs that actual password to create the database. Only the copy going to the Terminal is swapped for a masked placeholder. The secret itself never stopped being real.
Step 2: the copy nobody masks
There's a second path, though. Terraform has to remember every attribute it manages, so it can detect drift later. That means terraform apply also records the real S3cr3t! into terraform.tfstate. The Terminal gets the masked copy, but the state file gets the actual value.
terraform.tfstate (excerpt)
Here's the state file itself. The password line reads S3cr3t! in plain JSON, so anyone can see it with a simple cat. The sensitive_attributes list only tells the CLI what to mask in its output. It doesn't encrypt anything in the file.
{
"type": "aws_db_instance",
"name": "main",
"instances": [{
"attributes": {
"username": "admin",
"password": "S3cr3t!"
},
"sensitive_attributes": [ ... ]
}]
}Step 3: git push publishes it
The terminal only ever showed sensitive. But the same S3cr3t! flows into terraform.tfstate, and git push publishes that file to the GitHub repo. Now anyone with repo access can read the password. It also lives in every clone and in git history, and bots scan public repos for secrets within minutes.
Contain the leak, in this order
Rotate the password first, because deleting the file can't un-leak it. Then purge the state from history with git filter-repo or BFG, and force-push. Existing clones keep their copies. Finally, add the state files to .gitignore.
- Rotate the database password now
- Purge tfstate from git history
- Add *.tfstate* to .gitignore
backend.tf
Next, move state into an S3 backend. The encrypt setting protects it at rest, use_lockfile locks it during runs, assuming Terraform 1.10 or newer, and IAM policies decide who can read the bucket. From Terraform 1.11, write-only arguments can even keep some values out of state entirely.
terraform {
backend "s3" {
bucket = "acme-tf-state"
key = "prod/terraform.tfstate"
region = "us-east-1"
encrypt = true
use_lockfile = true
}
}Sensitive masks the terminal; the state file still holds plaintext.
Sensitive masks the terminal, but terraform.tfstate still holds the password in plaintext. Treat state like a secret store: keep it in an encrypted, access-controlled backend, and never commit it to a repo like GitHub.