Command to Apply Multiple .tfvars Files (Part-10)

Posted by

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_count will be set to 5 from prod.tfvars (overriding the value from dev.tfvars).
  • instance_type will be set to “t3.medium” from override.tfvars (overriding the value from both dev.tfvars and prod.tfvars).

Summary

  • Use the -var-file flag to specify multiple .tfvars files.
  • The order in which you specify the .tfvars files 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 in variable.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.

guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x