Terraform Tutorial — Sensitive Variables
Some variables contain secrets — database passwords, API keys, tokens. Marking them as sensitive prevents Terraform from displaying their values in plan output, apply output, and the terminal.
Marking a Variable as Sensitive
variable "db_password" {
type = string
description = "Database master password"
sensitive = true
}
When you run terraform plan, the value is redacted:
# aws_db_instance.main will be created
+ resource "aws_db_instance" "main" {
+ password = (sensitive value)
}
Providing Sensitive Values
Never put secrets in .tfvars files that are committed to Git. Instead:
Option 1: Environment Variable
$ export TF_VAR_db_password="super-secret-password"
$ terraform apply
Option 2: -var Flag
$ terraform apply -var="db_password=super-secret-password"
Option 3: CI/CD Secrets
In GitHub Actions:
- name: Terraform Apply
run: terraform apply -auto-approve
env:
TF_VAR_db_password: ${{ secrets.DB_PASSWORD }}
Sensitive Outputs
If an output references a sensitive value, you must also mark the output as sensitive:
output "db_connection_string" {
value = "postgresql://admin:${var.db_password}@${aws_db_instance.main.endpoint}/mydb"
sensitive = true
}
Without sensitive = true, Terraform refuses to display an output that contains a sensitive value:
Error: Output refers to sensitive values
Output "db_connection_string" includes a sensitive value. Mark the output
as sensitive with `sensitive = true`.
Important Limitations
⚠️ Warning: Sensitive variables are hidden from the terminal output, but they are still stored in plaintext in the state file. Always encrypt your state backend (S3 with SSE, Terraform Cloud) and restrict access to the state file.
| Protected | Not Protected |
|---|---|
terraform plan output |
State file (terraform.tfstate) |
terraform apply output |
Log files if TF_LOG is enabled |
terraform output display |
External data sources or provisioners |
What’s Next?
You’ve mastered variables. Time to test everything with the practice exercises.