Prompt
I'm building Terraform workflows and want to avoid putting secrets in code
Latest observation
Great goal. In Terraform workflows, the main rule is: don’t put secrets in .tf files, .tfvars, or hardcoded module defaults.
Here are the common patterns to keep secrets out of code:
Good options
1) Use environment variables
For sensitive inputs, pass values via environment variables instead of committing them.
export TF_VAR_db_password="supersecret"
terraform apply
Then in Terraform:
variable "db_password" {
type = string
sensitive = true
}
2) Use secret managers
Store secrets in a proper secret store and retrieve them at runtime:
- AWS Secrets Manager
- HashiCorp Vault
- Azure Key Vault
- GCP Secret Manager
- Kubernetes Secrets (for some cases)
Terraform can read from these using data sources or provider integrations.
3) Mark variables as sensitive
This won’t prevent the secret from existing in state, but it reduces accidental exposure in CLI output:
variable "api_key" {
type = string
sensitive = true
}
4) Keep secrets out of state where possible
Terraform state can still contain secrets if a resource or data source returns them. To reduce risk:
- Use providers/resources that don’t echo secrets back unnecessarily
- Store state in a secure remote backend
- Encrypt state at rest
- Restrict access tightly
5) Use .gitignore for local secret files
If you must use local .tfvars files, don’t commit them:
*.tfvars
*.tfvars.json
And keep a non-secret example file in repo, like:
example.tfvars
What to avoid
- Hardcoding secrets in
.tffiles - Committing
.tfvarswith real values - Printing secrets in
outputblocks - Storing secrets in plaintext state files or logs
- Putting secrets in CI logs
Practical recommendation
A strong default approach is:
- Use Terraform variables for secret values
- Source them from environment variables in local dev
- Source them from a secret manager in CI/CD
- Use a remote encrypted backend for state
If you want, I can show you:
- a Terraform example using
TF_VAR_*, - a Vault / AWS Secrets Manager example, or
- a secure CI/CD pattern for Terraform secrets.