Sobes.tech
Middle

What is the priority of using variables in Terraform?

sobes.tech AI

Answer from AI

Priority of variable usage in Terraform: from highest to lowest:

  1. Environment variables.
  2. Command line (parameters -var or -var-file).
  3. Variable files (terraform.tfvars, *.auto.tfvars, terraform.tfvars.json, *.auto.tfvars.json).
  4. Variables declared in variables.tf files or *.tf files within the variable block, without override. In this case, the default value is used if specified.

Example with environment variable:

# Setting environment variable
export TF_VAR_instance_type="t2.medium"

Example with command line:

# Passing variable directly
terraform apply -var="instance_type=t2.large"

# Passing variables from a file
terraform apply -var-file="dev.tfvars"

Example of a terraform.tfvars variable file:

# Variable in terraform.tfvars file
instance_type = "t2.small"

Example of declaring a variable in variables.tf:

variable "instance_type" {
  description = "EC2 instance type"
  type        = string
  default     = "t2.micro" # Default value
}