The distinction between these is of declaration vs. assignment.
variable
blocks (which can actually appear in any .tf
file, but are in variables.tf
by convention) declare that a variable exists:
variable "example" {}
This tells Terraform that this module accepts an input variable called example
. Stating this makes it valid to use var.example
elsewhere in the module to access the value of the variable.
There are several different ways to assign a value to this input variable:
- Include
-var
options on the terraform plan
or terraform apply
command line.
- Include
-var-file
options to select one or more .tfvars
files to set values for many variables at once.
- Create a
terraform.tfvars
file, or files named .auto.tfvars
, which are treated the same as -var-file
arguments but are loaded automatically.
- For a child module, include an expression to assign to the variable inside the calling
module
block.
A variable can optionally be declared with a default value, which makes it optional. Variable defaults are used for situations where there's a good default behavior that would work well for most uses of the module/configuration, while still allowing that behavior to be overridden in exceptional cases.
The various means for assigning variable values are for dealing with differences. What that means will depend on exactly how you are using Terraform, but for example if you are using the same configuration multiple times to deploy different "copies" of the same infrastructure (environments, etc) then you might choose to have a different .tfvars
file for each of these copies.
Because terraform.tfvars
and .auto.tfvars
are automatically loaded without any additional options, they behave similarly to defaults, but the intent of these is different. When running Terraform in automation, some users have their automation generate a terraform.tfvars
file or .auto.tfvars
just before running Terraform in order to pass in values the automation knows, such as what environment the automation is running for, etc.
The difference between the automatically-loaded .tfvars
files and variable defaults is more clear when dealing with child modules. .tfvars
files (and -var
, -var-file
options) only apply to the root module variables, while variable defaults apply when that module is used as a child module too, meaning that variables with defaults can be omitted in module
blocks.