šŸ¶
Terraform

Terraform tfvars vs variables.tf: What's the Difference?

By Filip on 10/07/2024

Learn the key differences between terraform.tfvars and variables.tf for managing your Terraform project variables effectively.

Terraform tfvars vs variables.tf: What's the Difference?

Table of Contents

Introduction

In Terraform, managing your infrastructure involves working with variables to make your configurations adaptable. You'll encounter variables.tf files and Terraform variable files (.tfvars), each serving a distinct purpose in how you define and assign values to these variables.

Step-by-Step Guide

Let's break down the difference between variables.tf and Terraform variable files (.tfvars):

Think of it like this:

  • variables.tf is where you declare your variables. It's like creating a blueprint and saying, "I'm going to need these pieces of information later."
  • .tfvars files are where you actually assign values to those variables. This is like filling in the blueprint with specific measurements and materials.

Here's a closer look:

  1. variables.tf

    • You define variables within variable blocks.
    • You can specify a variable's type (like string, number, list, etc.) to ensure you're getting the right kind of data.
    • You can set default values here. If a variable has a default, you don't have to provide it in a .tfvars file.
  2. .tfvars files

    • These files have a simple format: variable_name = value
    • You can have multiple .tfvars files:
      • terraform.tfvars: Terraform automatically loads this one.
      • Custom named files: Useful for different environments (e.g., dev.tfvars, prod.tfvars). You load these with terraform apply -var-file=prod.tfvars.

Why is this separation useful?

  • Flexibility: You can reuse your Terraform code with different settings just by changing the .tfvars file. This is great for managing multiple environments (development, staging, production) without code duplication.
  • Security: Sensitive data (like passwords) should never go directly in your .tf files. .tfvars files provide a way to keep this information separate and potentially out of version control if needed.

Key takeaways:

  • Declaration vs. Assignment: variables.tf for declaring, .tfvars for assigning.
  • Flexibility and Reusability: Easily switch configurations using different .tfvars files.
  • Security Best Practice: Keep sensitive data out of your main codebase.

Code Example

This code demonstrates how to create an AWS EC2 instance using Terraform, showcasing the use of variables and .tfvars files for configuration. It defines variables for region, instance type, AMI ID, and SSH key name in variables.tf. A terraform.tfvars file provides values for required variables. The main.tf file utilizes these variables to define the EC2 instance resource. The example also illustrates using a separate .tfvars file (dev.tfvars) to override default values for different environments, promoting code reusability and organization.

Let's say you want to create an EC2 instance on AWS using Terraform. Here's how you'd use variables.tf and .tfvars files:

1. variables.tf (Declaring Variables)

variable "aws_region" {
  type = string
  default = "us-east-1"
}

variable "instance_type" {
  type = string
  default = "t2.micro"
}

variable "ami_id" {
  type = string
}

variable "ssh_key_name" {
  type = string
}
  • We declare four variables:
    • aws_region: The AWS region for the instance (defaulting to us-east-1).
    • instance_type: The EC2 instance type (defaulting to t2.micro).
    • ami_id: The ID of the Amazon Machine Image (AMI) to use. This one has no default, so it must be provided.
    • ssh_key_name: The name of the SSH key pair for accessing the instance.

2. terraform.tfvars (Assigning Values)

ami_id = "ami-0c55b31ad2299a5fd"
ssh_key_name = "my-key-pair"
  • We provide values for the required variables (ami_id and ssh_key_name).
  • Since aws_region and instance_type have defaults in variables.tf, we don't need to specify them here unless we want to override the defaults.

3. main.tf (Using the Variables)

resource "aws_instance" "my_instance" {
  ami           = var.ami_id
  instance_type = var.instance_type
  key_name      = var.ssh_key_name
  # ... other instance configurations ...
}
  • In our main Terraform code, we reference the variables using var.variable_name.

4. Using a Different Environment (dev.tfvars)

ami_id = "ami-0a1bc2d3ef456gh7i" 
ssh_key_name = "my-dev-key-pair"
instance_type = "t3.small" # Override the default instance type
  • We create a separate .tfvars file for a development environment.
  • We can override specific values (like instance_type) while reusing the same variables.tf and main.tf files.
  • To apply this configuration, we'd run: terraform apply -var-file=dev.tfvars

Benefits:

  • We can easily switch between environments by using different .tfvars files.
  • We keep sensitive data like SSH key names separate from the main codebase.
  • Our Terraform code is more organized and reusable.

Additional Notes

  • Think of variables like function arguments: In programming, you define a function with parameters (variables) and then pass in specific values when you call the function. .tfvars files are how you "pass in" values to your Terraform code.
  • Version Control: It's generally a good practice to keep your .tf files (including variables.tf) in version control. You can choose to version control your .tfvars files as well, but be extremely careful about storing sensitive data in them if you do.
  • Alternatives for Sensitive Data:
    • Environment variables: You can pass sensitive values to Terraform using environment variables.
    • Secret management tools: For production environments, consider dedicated secret management solutions like HashiCorp Vault, AWS Secrets Manager, or Azure Key Vault.
  • Variable Validation: You can add validation rules to your variables in variables.tf to enforce constraints on the values that can be assigned. This helps prevent errors caused by incorrect input.
  • Organization and Structure: For larger projects, it's helpful to organize your Terraform code into modules. Each module can have its own variables.tf file, making your code more modular and maintainable.
  • Terraform 0.12 and Beyond: While these concepts apply to all Terraform versions, Terraform 0.12 introduced improved variable type handling and validation, making your code even more robust.

By understanding the distinction between variables.tf and .tfvars files, you can write cleaner, more flexible, and secure Terraform code for managing your infrastructure.

Summary

Feature variables.tf .tfvars Files
Purpose Declare variables (define their name and type) Assign values to declared variables
Analogy Blueprint: outlining what information is needed Filling in the blueprint: providing specific values
Syntax variable blocks with type and optional default values variable_name = value
File Types Single file Multiple files possible: terraform.tfvars (auto-loaded) and custom named files (e.g., dev.tfvars)
Benefits
Flexibility Define variables once, reuse code with different values in .tfvars for various environments Easily switch configurations by loading different .tfvars files
Security Store sensitive data separately from code, potentially outside version control

In short: variables.tf sets the stage, .tfvars files direct the play. This separation enhances code reusability, flexibility, and security in Terraform projects.

Conclusion

In conclusion, understanding the roles of variables.tf and .tfvars files is crucial for writing effective and maintainable Terraform code. While variables.tf acts as a blueprint where you declare your variables and their types, .tfvars files serve as the actual input, providing specific values for those variables. This separation not only enhances code organization but also introduces flexibility, allowing you to reuse the same codebase across different environments by simply switching out the .tfvars file. Moreover, this approach promotes security by enabling you to store sensitive data separately from your main codebase, potentially outside version control. By mastering this fundamental concept of variable declaration and assignment, you can unlock the full potential of Terraform and streamline your infrastructure management workflows.

References

Were You Able to Follow the Instructions?

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