šŸ¶
Terraform

Terraform Variables: tfvars vs variables.tf Explained

By Filip on 10/07/2024

Learn the key differences between variables.tf and terraform.tfvars and how to use them effectively in your Terraform projects.

Terraform Variables: tfvars vs variables.tf Explained

Table of Contents

Introduction

In Terraform, variables.tf and .tfvars files both handle variables, but they serve different purposes. Think of variables.tf as the blueprint where you declare your variables by specifying their name, data type, description, and an optional default value. On the other hand, .tfvars files are designed to hold the actual values for your variables, which Terraform uses during code execution. You can have multiple .tfvars files for different environments or to organize your values. While variables.tf defines the structure and documentation for your variables, .tfvars files provide flexibility and control over the actual values used during Terraform runs.

Step-by-Step Guide

In Terraform, variables.tf and .tfvars files both handle variables, but they serve different purposes.

Think of variables.tf as the blueprint. You use it to declare your variables. This means you'll specify the variable's name, its data type (like string, number, etc.), maybe a brief description, and optionally a default value.

Here's how a variables.tf declaration might look:

variable "location" {
  type = string
  description = "Azure region to deploy resources"
  default = "eastus"
}

On the other hand, .tfvars files (like terraform.tfvars) are designed to hold the actual values for your variables. These values are what Terraform uses when running your code. You can have multiple .tfvars files for different environments (e.g., dev.tfvars, prod.tfvars) or to organize your values logically.

A simple terraform.tfvars might look like this:

location = "westus2" 

In this example, even though variables.tf sets a default location, Terraform will use "westus2" because the .tfvars file takes precedence.

Here's a breakdown of when to use each:

  • variables.tf:
    • Defining variable names, types, descriptions, and optional defaults.
    • Providing a clear structure and documentation for your variables.
  • .tfvars files:
    • Setting specific values for your variables.
    • Keeping sensitive data (like passwords) out of your main code.
    • Managing configurations for different environments or deployments.

Remember, while you can set default values in variables.tf, .tfvars files give you flexibility and control over the actual values used during Terraform runs.

Code Example

This code demonstrates how to use variables in Terraform to create an Azure Resource Group. It defines two variables in variables.tf: resource_group_name and location. The terraform.tfvars file provides values for these variables. The main.tf file uses these variables to define the Azure Resource Group resource. This approach allows for reusable and configurable infrastructure code.

This example creates an Azure Resource Group using Terraform.

1. variables.tf:

variable "resource_group_name" {
  type = string
  description = "Name of the resource group"
}

variable "location" {
  type = string
  description = "Azure region to deploy resources"
  default = "eastus"
}

2. terraform.tfvars:

resource_group_name = "my-rg"
location = "westus2"

3. main.tf:

terraform {
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "~> 3.0"
    }
  }
}

resource "azurerm_resource_group" "rg" {
  name     = var.resource_group_name
  location = var.location
}

Explanation:

  • variables.tf: Defines two variables: resource_group_name (required) and location (optional with a default value).
  • terraform.tfvars: Provides the actual values for both variables. Notice how location overrides the default value defined in variables.tf.
  • main.tf: Uses the variables defined in variables.tf and assigned values from terraform.tfvars to create an Azure Resource Group.

Running the code:

  1. Save the above code snippets as variables.tf, terraform.tfvars, and main.tf respectively in the same directory.
  2. Run terraform init to initialize the working directory.
  3. Run terraform plan to see the execution plan.
  4. Run terraform apply to create the resource group.

This example demonstrates how to define variables in variables.tf, assign values in terraform.tfvars, and use them in your Terraform code. You can create multiple .tfvars files for different environments or scenarios and pass them to Terraform using the -var-file flag.

Additional Notes

  • Clarity and Organization: Using separate variables.tf and .tfvars files enhances code readability and maintainability. It separates the variable definitions from their actual values, making it easier to understand the purpose and structure of your variables.
  • Reusability: You can reuse the same variables.tf file across different environments or projects, while customizing the values using different .tfvars files. This promotes consistency and reduces code duplication.
  • Sensitive Data Protection: Never store sensitive data like passwords, API keys, or secret keys directly in your variables.tf or .tfvars files. Instead, use secure methods like HashiCorp Vault or environment variables to manage and inject sensitive information.
  • Variable Validation: Terraform allows you to add validation rules to your variables within the variables.tf file. This helps ensure that the values provided in .tfvars files meet specific criteria, improving the reliability of your infrastructure deployments.
  • Command-Line Inputs: While .tfvars files are commonly used, you can also pass variable values directly from the command line using the -var flag during Terraform runs. This is useful for quick overrides or testing purposes.
  • Remote Storage of .tfvars: For enhanced security and centralized management, consider storing your .tfvars files in remote storage solutions like AWS S3, Azure Blob Storage, or HashiCorp Consul. This allows for secure access and version control of your configuration data.
  • Auto-Loading .tfvars Files: Terraform automatically loads files named terraform.tfvars or *.auto.tfvars in the current working directory. You can use this feature for default values or common configurations.
  • Variable Interpolation: Terraform allows you to use variables within other variables or resource definitions. This dynamic behavior enables flexible and reusable configurations.
  • Modules and Variables: When working with Terraform modules, you can pass variables to customize the module's behavior. This promotes code reusability and allows you to create modular and adaptable infrastructure components.

Summary

Feature variables.tf .tfvars
Purpose Declaring variables: defining names, types, descriptions, and optional defaults Assigning values to variables for actual use during Terraform runs
Content Variable definitions with types, descriptions, and optional defaults Key-value pairs where the key is the variable name and the value is the assigned value
Usage Provides a blueprint and documentation for your variables Provides flexibility in setting specific values for different environments or deployments
Example variable "location" { type = string } location = "westus2"
Precedence Default values can be overridden Values in .tfvars files take precedence over defaults defined in variables.tf

In essence:

  • Use variables.tf to define what your variables are.
  • Use .tfvars files to define how those variables are used in different contexts.

Conclusion

By effectively using variables.tf for variable declaration and .tfvars files for value assignment, you can create adaptable, maintainable, and robust infrastructure as code with Terraform. These practices contribute to better organization, promote code reusability, and enhance the security of your deployments. Remember to leverage Terraform's capabilities for variable validation, remote storage, and integration with modules to further streamline your infrastructure management workflows.

References

Were You Able to Follow the Instructions?

šŸ˜Love it!
šŸ˜ŠYes
šŸ˜Meh-gical
šŸ˜žNo
šŸ¤®Clickbait