🌩️ Mastering variables.tf in Terraform with Real Examples

BinereetDevopsBinereetDevops
2 min read

Terraform is a powerful Infrastructure as Code tool, and one of its superpowers lies in using variables to make configurations clean, reusable, and flexible.

In this blog, we’ll dive into the variables.tf file in Terraform and walk through a real-world example to understand how to define and use variables like a pro!


🌱 What is variables.tf?

The variables.tf file is where you define input variables for your Terraform configuration. These variables allow you to avoid hardcoding values and instead pass them dynamically when applying the configuration.

This helps you:

  • Keep your code modular and DRY (Don’t Repeat Yourself)

  • Easily reuse configurations in different environments

  • Manage sensitive data or frequently changed settings


✍️ Example variables.tf

Here’s a simple snippet defining three variables:

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

variable "ec2_root_storage_size" {
  default = 15
  type    = number
}

variable "ec2_ami_id" {
  default = "ami-0cb91c7de36eed2cb"
  type    = string
}

🔍 Explanation:

  • ec2_instance_type: Defines the EC2 instance type as a string with default t2.micro.

  • ec2_root_storage_size: A numeric value to set root volume size (in GB), default is 15.

  • ec2_ami_id: Specifies the Amazon Machine Image ID to launch.


⚙️ Using Variables in main.tf

Once you define variables, you can reference them using the var. prefix like so:

resource "aws_instance" "my_instance" {
  key_name        = aws_key_pair.my_key.key_name
  security_groups = [aws_security_group.my_security_group.name]
  instance_type   = var.ec2_instance_type
  ami             = var.ec2_ami_id

  root_block_device {
    volume_size = var.ec2_root_storage_size
    volume_type = "gp3"
  }

  tags = {
    Name = "TWS-Junoon-automate"
  }
}

This structure allows you to dynamically configure your AWS instance using the input values provided in variables.tf.


✅ Summary

  • Use variables.tf to define input variables cleanly.

  • Reference them in your resources with var.<variable_name>.

  • Keep your configs dynamic, maintainable, and easy to scale.

  • Always double-check variable names!

🌟 Whether you're a DevOps beginner or polishing your Terraform setup, mastering variables.tf is essential. Happy Terraforming!

My linkedIn Profile - https://www.linkedin.com/in/binereet-singh-9a7685316/

0
Subscribe to my newsletter

Read articles from BinereetDevops directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

BinereetDevops
BinereetDevops