Skip to content

Understanding Terraform: variables.tf vs variables.tfvars

Understanding the roles of variables.tf and variables.tfvars is crucial for effective Terraform configuration management.

1. variables.tf: Declaring Input Variables

The variables.tf file is where you declare and define input variables for your Terraform configuration. Input variables act as parameters that allow users to customize settings without modifying the underlying infrastructure code. Let’s take a closer look at the components of a variables.tf file:

# variables.tf

variable "project_id" {
  description = "The project ID to host the network in"
  default     = "YOUR PROJECT ID"
  type        = string
}

variable "network_name" {
  description = "The name of the VPC network being created"
  default     = "example-vpc"
  type        = string
}

In this example, we’ve defined two variables:project_id and network_name. The description provides context, type specifies the data type, and default sets a default value.

2. variables.tfvars: Assigning Variable Values

While variables.tf defines the structure of your variables, the variables.tfvars file assigns specific values to those variables. This separation allows you to customize configurations for different environments or use cases without altering the underlying Terraform code.

# terraform.tfvars

region        = "us-west-1"
instance_type = "e2-standard-2"

In this example, we’ve created a terraform.tfvars file, providing values for region and instance_type. When Terraform commands like terraform apply or terraform plan are executed, the values from this file will be used.

Benefits of Separation

Separating variable declarations (variables.tf) from variable values (variables.tfvars) brings several advantages:

Reusability:

Reuse the same infrastructure code across different environments by providing specific values in separate .tfvars files.

Clarity:

Maintain a clear distinction between the configuration structure and environment-specific values, making the codebase more readable.

Version Control:

Easily manage and version control your infrastructure code without worrying about sensitive or environment-specific information.

As you dive deeper into Terraform, keep in mind the power of variables and their dedicated files in orchestrating infrastructure deployments efficiently.