Define Sensitive Database Credential Variables

Create Terraform variables for database username and password with sensitive flag, length validation, and no default values for secrets.

Common Patterns

Detailed Explanation

Database Credential Variables

Database credentials are the most common example of sensitive variables in Terraform. They require special handling to prevent exposure in plan output, state files, and logs.

Variable Definitions

variable "db_username" {
  type        = string
  description = "Master username for the database"

  validation {
    condition     = length(var.db_username) >= 3 && length(var.db_username) <= 63
    error_message = "Database username must be between 3 and 63 characters."
  }
}

variable "db_password" {
  type        = string
  description = "Master password for the database"
  sensitive   = true

  validation {
    condition     = length(var.db_password) >= 8
    error_message = "Database password must be at least 8 characters."
  }
}

Key Design Decisions

  1. No default for password: Sensitive values should never have defaults in code
  2. No default for username: Avoids accidental use of a generic admin name
  3. sensitive = true on password: Redacts value from CLI output
  4. Length validation: Catches obviously wrong values before AWS rejects them

Providing Values Securely

Option 1: tfvars file (gitignored)

# secrets.tfvars (NOT committed to git)
db_username = "app_admin"
db_password = "SuperSecretP@ssw0rd!"

Option 2: Environment variables

export TF_VAR_db_username="app_admin"
export TF_VAR_db_password="SuperSecretP@ssw0rd!"

Option 3: Terraform Cloud / HCP variables Mark the variable as "Sensitive" in the Terraform Cloud workspace settings.

What sensitive = true Does

  • Redacts the value in terraform plan output: db_password = (sensitive value)
  • Redacts in terraform output if referenced
  • Does NOT encrypt the value in state — use encrypted backends (S3 + KMS, etc.)
  • Does NOT prevent the value from being logged by the provider itself

Use Case

RDS, Aurora, or any database module where credentials must be passed securely, never hardcoded in source, and redacted from Terraform CLI output.

Try It — Terraform Variable Generator

Open full tool