Skip to main content

Variable Definition Precedence in Terraform

Note: This article is for my own reference.

In Terraform, it is possible to use several methods of setting variables in any combination. That always confuses me, so I kept it here to refer back to it instead of looking into Terraform documentation.

Terraform will use the last value found and override any previous values if a variable is assigned multiple values. Remember that a variable cannot be assigned multiple values within a source.

Terraform loads variables in the following order: later sources take precedence.

  • Environment variables
  • The terraform.tfvars file, if present.
  • The terraform.tfvars.json file, if present.
  • Any *.auto.tfvars or *.auto.tfvars.json files, processed in lexical order of their filenames.
  • Any -var and -var-file options on the command line, in the order they are provided. (This includes variables set by a Terraform Cloud workspace.)
# file: variables.tf

variable "host_os" {
  type = string
  default = "windows"
}
# output
terraform console
> var.host_os # printing the value of variable "host_os"
"windows" # <= this is the output

You can override the above values using terraform.tfvars file

# file: terraform.tfvars
host_os = "linux"
# output
terraform console
> var.host_os
"linux" # <= this is the output

Command Line will take precedence over the terraform.tfvars

# directly over the command-line
$ terraform console -var="host_os=osx"
> var.host_os
"osx" # <= this is the output

# file: dev.tfvars
host_os = "ChromeOS"

terraform.tfvars will take precedence over dev.tfvars. See the output; it is NOT ChromeOS as variables from terraform.tfvars overrides.

$ terraform console
> var.host_os
"linux" # <= this is the output, not the "ChromeOS"
# directly over the command-line

$ terraform console -var-file="dev.tfvars"
> var.host_os
"ChromeOS" # <= this is the output

Important: In Terraform version 0.12 or later, variables containing map or object values now behave like other variables, where the last value found will override all previous values. This is a change from earlier versions of Terraform, where map values would merge instead of overriding each other.

Variable precedence within Terraform tests

When working with Terraform test files, you have the option to define variable values within variables blocks. These blocks can be nested within run blocks or defined directly within the file.

It is important to note that variables defined in this way take precedence over all other mechanisms during test execution. In cases where variables are defined within both run blocks and the file itself, the variables defined within the run block will take precedence.


Post Tags: