पाठ 18 / 25
Keeping Secrets Out of Code and Safe in State
Where secrets should live.
Secret managers and protected backends
Never put secrets in .tf or committed .tfvars files. Pass them through environment variables (TF_VAR_db_password), read them from a secret manager data source, or better, let the platform generate and store them (for example a managed database password kept in a secrets manager, never handled by Terraform). Because state can still contain secrets, use an encrypted remote backend with strict access control, and newer features such as ephemeral values where your Terraform version supports them.
Safer secret handling (sketch)
Not run here; it needs a cloud account or a remote backend. Feature availability varies by provider and Terraform version.
# read an existing secret at plan/apply time instead of hard-coding it
data "aws_secretsmanager_secret_version" "db" {
secret_id = "shop/prod/db"
}
# or let the service manage the password itself
resource "aws_db_instance" "main" {
# ...
manage_master_user_password = true # stored and rotated in Secrets Manager
}Treat state as a secret
Limit who can read the state bucket as tightly as you would limit access to the production database.
त्वरित जाँच: Where should a database password NOT be stored?
- In a committed .tf or .tfvars file
- In a secrets manager
- In an encrypted, access-controlled state backend if unavoidable
- In an environment variable on the CI runner for the run
Answer
In a committed .tf or .tfvars file — Never commit secrets.