Terraform · Infrastructure as code

How should you handle secrets in Terraform?

Mediumsecretssensitive datastateUpdated Oct 2026
Quiz this track

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.

hcl
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"]
}
Reading from a secret manager avoids committing the value, but the decoded value can still land in state if used in a resource.

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.

Rotating a secret through Terraform can be awkward because the old value may remain in state history. Prefer rotation in the secret manager and let Terraform reference the current version.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1Does sensitive = true keep a value out of state?
  2. 2How do you rotate a database password managed by Terraform?
  3. 3What are ephemeral resources and write-only arguments?
  4. 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.