Interview Infrastructure as Code (Terraform, Ansible)

How do you manage secrets in Terraform without leaking them into state?

Infrastructure as Code (Terraform, Ansible) · Intermediate level

Answer

You cannot completely avoid secret values in Terraform state if Terraform manages a resource attribute that stores the secret. The safer pattern is to avoid generating or passing plaintext secrets through Terraform, reference secret ARNs or names instead of values, restrict state access, encrypt state, and let runtime systems fetch secrets directly.

Technical explanation

Marking a value sensitive hides output but does not remove it from state.

If Terraform must set a secret value, assume state readers can see it and govern access accordingly.

Prefer secret metadata and runtime retrieval over secret material in IaC.

Keep Terraform's ownership boundary clear: one state should own a resource or field, and other tools should consume published outputs instead of modifying it.

Use fmt, validate, linting, policy checks, plan review, and state locking before production applies.

Design for small blast radius by splitting state around lifecycle, permissions, and recovery boundaries.

Hands-on example

1. Harden secret handling for: How do you manage secrets in Terraform without leaking them into state?

2. Bad pattern: passing plaintext database passwords as Terraform variables and outputting them.

3. Better pattern: create or reference secret metadata and let runtime fetch the value:

resource "aws_secretsmanager_secret" "db" { name = "prod/db/password" }

# Application IAM can read this secret ARN; Terraform does not need to output the value.

output "db_secret_arn" { value = aws_secretsmanager_secret.db.arn }

4. Mark any unavoidable sensitive input or output with sensitive = true, but still treat the state backend as secret storage.

5. Verify S3 state encryption, IAM read restrictions, audit logs, and CI log redaction.

Preparing for an interview?

Check how well your resume matches the role with our free resume checker— match score, ATS check, and the skills you're missing.

More Infrastructure as Code (Terraform, Ansible) interview questions

← All Infrastructure as Code (Terraform, Ansible) questions