Terraform · Infrastructure as code
How should you handle secrets in Terraform?
Short answer
Keep secrets out of version control and pass them at runtime through a secret manager, CI secret store or environment variables. Marking a variable sensitive hides it from output but does not remove it from state.
Terraform needs secrets to configure some resources, but it is not a secret manager. Values passed into resources are generally written to state, and some are visible in plan output. The goal is to minimise what enters Terraform and to control where it is stored.
variable "db_password" {
type = string
sensitive = true
}
data "aws_secretsmanager_secret_version" "db" {
secret_id = "prod/db/password"
}
locals {
db_password = jsondecode(data.aws_secretsmanager_secret_version.db.secret_string)["password"]
}Practical options
- CI secret store or environment variables injected at runtime
- Cloud secret manager read through a data source or external secret operator
- Short-lived credentials from OIDC or workload identity
- Ephemeral resources and write-only arguments where the provider supports them
Marking a value sensitive redacts it from CLI output and plan diffs, but it does not encrypt state, remove it from state, or stop a determined reader. Restrict state access, enable encryption, and avoid outputs that expose secrets unless a consumer truly needs them.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Does sensitive = true keep a value out of state?
- 2How do you rotate a database password managed by Terraform?
- 3What are ephemeral resources and write-only arguments?
- 4How do you stop secrets appearing in plan output?
Say it in the interview
I keep secrets out of Git and inject them at runtime from a secret manager or CI secret store. Marking a variable sensitive only redacts display; the value can still be in state, so I restrict state access and encryption too. Where possible I use short-lived credentials or ephemeral values. For rotation, I prefer rotating in the secret manager and referencing the current version rather than storing each value in Terraform.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Terraform mock interview and get scored feedback on depth, clarity and confidence.