DEV Community

Sainath Patil
Sainath Patil

Posted on

Terraform Variables

One simple Question everyone has

  1. What are Variables
  2. Why to use Variables
  3. After these two questions, you will be good enough to understand what problems variables solve

What Are Variables in Terraform?
Think of a variable as a placeholder, a small container that stores a value.
That’s it.

variable "region" {
  description = "AWS region"
}
Enter fullscreen mode Exit fullscreen mode

This creates a variable called region.

Later you will assign the actual value like:

region = "ap-south-1"
Enter fullscreen mode Exit fullscreen mode

It’s just like writing:

  • “Hey Terraform, be ready to use some value later called region.”

Why Do We Use Variables?

Imagine you are deploying resources (like EC2, VPC, S3).
Without variables, you'd repeat values everywhere:

  • region
  • instance type
  • environment name
  • CIDR blocks

If any value changes, you'd manually edit multiple files.
That’s messy.

Variables solve this by letting you define once and use many times.

Without Variables (messy)

resource "aws_instance" "example" {
  ami           = "ami-123"
  instance_type = "t3.micro"
  region        = "ap-south-1"
}

Enter fullscreen mode Exit fullscreen mode

If you want to change region, you must change it everywhere.

With Variables (clean)

variable "region" {}
variable "instance_type" {}

resource "aws_instance" "example" {
  ami           = "ami-123"
  instance_type = var.instance_type
  provider      = aws
}

Enter fullscreen mode Exit fullscreen mode

Now your values stay in one file like:

region        = "ap-south-1"
instance_type = "t3.micro"
Enter fullscreen mode Exit fullscreen mode

Change once -> reflected everywhere.

What Problems Do Terraform Variables Solve?

  • Reusable
  • Easier to maintain
  • Cleaner
  • Safer

Conclusion (In One Line)
Terraform variables let you write clean, reusable, and easy-to-update infrastructure code.

Top comments (0)