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:
- Environment variables.
- Command line (parameters
-varor-var-file). - Variable files (
terraform.tfvars,*.auto.tfvars,terraform.tfvars.json,*.auto.tfvars.json). - Variables declared in
variables.tffiles or*.tffiles within thevariableblock, without override. In this case, thedefaultvalue 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
}