In Terraform, the order of precedence for variable assignment determines which value is used when multiple sources are available. Here’s the order of precedence from lowest to highest:
1. Default Values in Variable Definitions (default
):
If no other value is provided, the default value defined in the variable block is used.
variable "region" {
type = string
description = "The region where resources will be deployed"
default = "us-west-1"
}
2. Environment Variables (TF_VAR_
):
Environment variables that follow the format TF_VAR_name
. For example, for the variable region
, you can set it in your execution environment as TF_VAR_region
.
export TF_VAR_region="us-east-1"
3. terraform.tfvars
or *.auto.tfvars
Files:
Terraform automatically looks for files named terraform.tfvars
or files with the .auto.tfvars
extension in the current directory and applies the values defined in them.
# terraform.tfvars
region = "us-east-1"
4. Specific Variable Files:
You can specify a custom variable file using the -var-file
flag on the command line.
terraform apply -var-file="custom.tfvars"
5. Command-Line Flags (-var
):
You can pass values directly on the command line using the -var
flag. This method has the highest precedence and will override any other defined values.
terraform apply -var="region=us-east-2"
Practical Example
Suppose you have a Terraform configuration with a variable named region
defined as follows:
# variables.tf
variable "region" {
type = string
description = "The region where resources will be deployed"
default = "us-west-1"
}
And you have the following files and configurations:
1. terraform.tfvars
File:
region = "us-east-1"
2. Custom Variable File custom.tfvars
:
region = "us-west-2"
3. Environment Variable:
export TF_VAR_region="eu-central-1"
4. Command-Line Flag:
terraform apply -var="region=us-east-2"
Precedence Order in Action
1. If you run terraform apply
without any other options:
The value from the terraform.tfvars
file (us-east-1
) will be used.
2. If you run terraform apply -var-file="custom.tfvars"
:
The value from the custom.tfvars
file (us-west-2
) will be used.
3. If you have the environment variable TF_VAR_region
set:
The value from the environment variable (eu-central-1
) will be used.
4. If you use the command-line flag -var
:
The value passed on the command line (us-east-2
) will be used, overriding any other value.
Summary
The order of precedence for variable assignment in Terraform is crucial to understanding which value will be used when multiple sources are available.
The precedence order from lowest to highest is:
- Default values in variable definitions.
- Environment variables (
TF_VAR_
). terraform.tfvars
or*.auto.tfvars
files.- Specific variable files (
-var-file
). - Command-line flags (
-var
).
This order allows you to control and override variable values flexibly according to your needs.