Here’s how you can specify multiple .tfvars files when running the terraform apply command:
terraform apply -var-file="file1.tfvars" -var-file="file2.tfvars" -var-file="file3.tfvars"
Example
Assume you have the following .tfvars files:
dev.tfvars
instance_count = 2
instance_type = "t2.micro"
prod.tfvars
instance_count = 5
instance_type = "t2.large"
override.tfvars
instance_type = "t3.medium"
Applying the Variables
To apply these variables in order, you would use:
In this example:
instance_countwill be set to 5 fromprod.tfvars(overriding the value fromdev.tfvars).instance_typewill be set to “t3.medium” fromoverride.tfvars(overriding the value from bothdev.tfvarsandprod.tfvars).
Summary
- Use the
-var-fileflag to specify multiple.tfvarsfiles. - The order in which you specify the
.tfvarsfiles matters; later files override earlier ones. - This approach allows you to manage complex configurations and overrides efficiently.
Note: If a value is defined in the variable.tf file, then the value from the .tfvars file will override the value defined in the variable.tf file
Explanation
variable.tf: This file defines variables and can provide default values for them..tfvars: This file provides values that override the defaults set invariable.tf.
In Terraform, the precedence order ensures that values from the .tfvars file override the defaults set in variable.tf.
Example
variable.tf:
variable "instance_type" {
description = "The type of instance to use"
type = string
default = "t2.micro"
}
custom.tfvars:
instance_type = "t2.large"
When you run Terraform with the custom.tfvars file:
terraform apply -var-file="custom.tfvars"
The value t2.large from custom.tfvars will override the default value t2.micro defined in variable.tf.