Variable Files and Environment Variables
Typing -var="environment=prod" -var="instance_type=t3.small" on every run is tedious and easy to get wrong. Terraform can read values from files and from the shell instead. The only tricky part is knowing which one wins when several disagree.
The rule
Default, environment, tfvars, auto, flags: the later one wins.
A variable definition file holds only assignments, no blocks:
# prod.tfvars
environment = "prod"
instance_type = "t3.small"Which files load:
terraform.tfvarsandterraform.tfvars.json— loaded automatically.- Any
*.auto.tfvarsor*.auto.tfvars.json— loaded automatically, in alphabetical order. - Any other file — only with
-var-file=prod.tfvars.
Keep one file per environment, such as staging.tfvars and prod.tfvars, and commit them, since they describe your environments. Nothing secret goes in them. Values must match the declared types, and a value for a variable that is declared nowhere produces a warning, which usually means a typo in the name.
Environment variables named TF_VAR_ plus the variable name also set values:
export TF_VAR_environment=staging
export TF_VAR_db_password='from-the-secret-store'This is the usual way to pass secrets in a pipeline without writing them into a file.
When several sources set the same variable, Terraform applies them in this order, and later overrides earlier:
- the
defaultin the variable block TF_VAR_environment variablesterraform.tfvars, thenterraform.tfvars.json*.auto.tfvarsfiles, alphabetically-varand-var-fileon the command line, in the order you typed them
Other TF_ environment variables tune Terraform itself rather than your configuration: TF_LOG=DEBUG turns on detailed logs, TF_INPUT=0 disables prompts, and TF_CLI_ARGS_plan adds default flags to every plan.
The shortcut
Picture a stack of sheets: the default at the bottom, the command line on top. Read the variable's value from the highest sheet that mentions it.
Bottom sheet
The variable's default is
"dev".
The trap: expecting the shell's TF_VAR_ to override a terraform.tfvars file. It is one of the lowest sources, just above the default.
Drills
Answer fast — trust the rule.
Which file is loaded without any flag?
How do you set the variable instance_type with an environment variable?
terraform.tfvars sets environment = "qa" and the shell has TF_VAR_environment=staging. With no flags, which value is used?
What does TF_LOG=DEBUG do?
Remember
- Order: default,
TF_VAR_,terraform.tfvars,*.auto.tfvars, flags. Later wins. - Shortcut: read the value from the highest sheet in the stack.
- Trap:
TF_VAR_is near the bottom; secrets go there, not into committed files.
