Define Sensitive Database Credential Variables
Create Terraform variables for database username and password with sensitive flag, length validation, and no default values for secrets.
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
- No default for password: Sensitive values should never have defaults in code
- No default for username: Avoids accidental use of a generic admin name
sensitive = trueon password: Redacts value from CLI output- 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 planoutput:db_password = (sensitive value) - Redacts in
terraform outputif 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
Related Topics
Define Project Name Variable with Naming Convention Validation
Common Patterns
Define Environment Name Variable with Allowed Values
Common Patterns
Define S3 Bucket Configuration as an Object Variable
Resource Configuration
Define Common Tags as a map(string) Variable
Common Patterns
Define Auto Scaling Configuration Variables
Resource Configuration