Variable Precedence and Overrides
You'll learn: How Terraform decides which variable value wins when multiple sources try to set the same variable.
The Precedence Hierarchy
You've learned many ways to supply variable values: default values in declarations, terraform.tfvars files, CLI flags, and environment variables. But what happens when the same variable is defined in multiple places?
Terraform follows a strict precedence order, from lowest to highest priority:
- Default values in variable declarations (lowest priority)
- Environment variables (
TF_VAR_*) terraform.tfvarsorterraform.tfvars.json(automatically loaded)*.auto.tfvarsfiles (alphabetically loaded)-var-fileflag(s) in command line (in order specified)-varflag(s) in command line (highest priority)
Think of It Like Layers
Imagine stacking transparent overlays. The bottom layer is your default value. Each method above it can overwrite what's below. The topmost visible value is what Terraform uses.
If you declare instance_type with default "t2.micro", set TF_VAR_instance_type="t2.small", and pass -var="instance_type=t2.medium", Terraform uses t2.medium because CLI flags beat everything.
Why This Matters
This hierarchy lets you:
- Set safe defaults in code
- Override per-environment with
.tfvarsfiles - Temporarily test different values with
-varflags - Keep secrets in environment variables that override file-based defaults
Key Takeaway: Terraform resolves variable conflicts using a strict precedence hierarchy where command-line flags have the highest priority and defaults in declarations have the lowest.