Course contentsShow
← Cloud and Infrastructure
Lesson 825 of 2,98915. Terraform in PracticeFree lesson

Managing Secrets in Terraform

Implement patterns for handling sensitive data including external secret stores and sensitive variable marking.

Managing Secrets in Terraform

What you'll learn: How to safely handle sensitive data like passwords, API keys, and tokens in your Terraform configurations without exposing them in plain text.


Why Secrets Need Special Care

Think of secrets like house keys—you don't leave them lying around or write them on sticky notes. In Terraform, hardcoding passwords or API tokens directly in .tf files is dangerous because those files often end up in version control, exposing your credentials to anyone with repository access.

Marking Variables as Sensitive

Terraform provides the sensitive argument in variable declarations. When a variable is marked sensitive, Terraform redacts its value in plan and apply output:

variable "database_password" {
  type      = string
  sensitive = true
}

This prevents accidental exposure in logs and console output, but the value still appears in state files.

External Secret Stores Pattern

Instead of storing secrets in Terraform configuration or state, retrieve them dynamically from dedicated secret management systems:

  • Use data sources to fetch secrets at runtime from AWS Secrets Manager, Azure Key Vault, or HashiCorp Vault
  • Pass secrets via environment variables (prefixed with TF_VAR_)
  • Keep actual secret values outside your Terraform codebase entirely
data "aws_secretsmanager_secret_version" "db_password" {
  secret_id = "prod/database/password"
}

resource "aws_db_instance" "main" {
  password = data.aws_secretsmanager_secret_version.db_password.secret_string
}

Layered Protection

Combine multiple strategies: mark variables as sensitive, use external secret stores, encrypt state files at rest, and restrict backend access with IAM policies.

Key Takeaway: Never hardcode secrets in Terraform files—use the sensitive variable flag for output protection and retrieve actual secrets from external secret management systems to keep credentials out of your codebase and minimize state file exposure.