📂

Understanding Terraform Variable Management

Mar 17, 2025

Lecture: Terraform Variable Definition Files and Usage

Variable Definition Files

  • Typically end with an extension .tfv or .tf.
  • Common file names: variables.tf, variables.tfi.
  • Define variables required by resources in a Terraform configuration.
  • Variables are defined in variable blocks, with names and values.

Purpose of Variable Definition Files

  • Used to assign values to variables defined in variables.tfi files.
  • Can be named flexibly (e.g., Franchesca.tfvars, Victor.tfvars).
  • Primarily for providing specific values for defined variables.

Using Variable Files for Different Environments

  • Helpful for deploying the same configuration in different environments (e.g., test, production).
  • Avoids hardcoding values within the main configuration.
  • Use different .tfvars files to pass different values suitable for each environment.

Example: Creating an EC2 Resource

  • EC2 resource requires an AMI.
  • Define a variable block in the variable file for the AMI ID.
  • Assign a value to the AMI ID in the .tfvars file.
  • Reference the variable in resource definition with var.<variable_name>.

Challenges without .tfvars Files

  • Hard to use the same block of code across multiple environments if values are embedded in the variable file.
  • Solution: separate variable definitions from their values.

Deployment Across Multiple Environments

  • Use terraform plan with -var-file=<file> to specify which .tfvars file to use.
  • Supports environments by having separate .tfvars for each (e.g., prod.tfvars, dev.tfvars).

Terraform Plan and Apply

  • terraform init: Initializes the directory.
  • terraform plan: Checks what infrastructure changes will be made.
  • terraform apply: Applies the changes to provision resources.

Advanced Concepts Discussed

  • Terraform Workspaces: Used for managing multiple environments without duplicating configurations. Workspaces allow you to create isolation for different states.
  • Output Values: Display attributes of the resources created, useful for debugging and configuration validation.
  • Variable Types: Lists, maps (objects), sets, strings, numbers (integers), booleans, and null values.
  • Resource Tagging: Challenges of tagging resources across multiple definitions and environments.

Key Takeaways

  • Ensure configurations are dynamic and reusable across environments.
  • Output values can help verify the infrastructure state and are crucial when working with modules.
  • Variable files and .tfvars files streamline managing different environments.
  • Organization of Terraform files into logical units helps manage and maintain configurations efficiently.