Terraform Secrets and Sensitive Values

How to handle credentials and secrets in Terraform without leaking them into state or version control.

What to avoid

Hardcoding secrets directly in .tf files is the most common mistake. Even in a private repository, credentials in source code are risky. They appear in git history and are easy to miss when rotating.

The second common mistake is committing terraform.tfvars files that contain real credentials. A tfvars file looks harmless until it ends up in a shared repository or CI log.

Common safer patterns

The three most practical approaches for beginners are environment variables, external secret stores, and sensitive variable declarations.

Environment variables — Terraform reads any environment variable named TF_VAR_<variable_name> at runtime. Set them in your shell session or CI/CD pipeline and they never touch a file.

Sensitive variable declarations — Add sensitive = true to the variable block. Terraform will then redact the value from plan, apply, and output logs.

variable "db_password" {
  type      = string
  sensitive = true
}
Sensitive variables improve output handling but do not encrypt the state file. Always combine them with a secure remote backend.

External secret stores — Tools like HashiCorp Vault, AWS Secrets Manager, or Azure Key Vault can supply values to Terraform at apply time using data sources. This keeps secrets out of Terraform files entirely.

A practical team approach

  1. Never put secrets in .tf or .tfvars files tracked by git.
  2. Use TF_VAR_ environment variables for local development.
  3. Use your CI/CD platform's secret store for pipeline runs.
  4. Mark all sensitive variables with sensitive = true.
  5. Store state in a remote backend with encryption and access control.