Course contentsShow
← Cloud and Infrastructure
Lesson 762 of 2,98914. Terraform FundamentalsFree lesson

Variable Precedence and Overrides

Understand how Terraform resolves variables when multiple sources provide values.

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:

  1. Default values in variable declarations (lowest priority)
  2. Environment variables (TF_VAR_*)
  3. terraform.tfvars or terraform.tfvars.json (automatically loaded)
  4. *.auto.tfvars files (alphabetically loaded)
  5. -var-file flag(s) in command line (in order specified)
  6. -var flag(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 .tfvars files
  • Temporarily test different values with -var flags
  • 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.