Learn Terraform Variables: A Simple Explanation
Terraform with AWS : Day - 5

A clear guide to variables, locals, data types, and how values flow in Terraform
Terraform variables help make your code flexible and reusable. Instead of hardcoding values, you can pass them from outside or define them in one place. This makes your infrastructure easier to manage and safer to change.
What are Terraform Variables
Variables are like placeholders for values. You define a variable once and reuse it in many places.
Real life example:
Think of variables like a contact saved as “Home Address” in your phone. If the address changes, you update it in one place instead of editing it everywhere.
Sample code:
variable "region" {
description = "AWS region"
type = string
default = "ap-south-1"
}
Variables and Locals
Locals are different from variables. Variables take input from outside. Locals are values calculated or defined inside your Terraform code.
Use variables when you want the value to come from users, CLI, or environment.
Use locals when you want to build reusable internal values.
Sample code:
locals {
app_name = "my-app"
full_name = "${local.app_name}-service"
}
You then use them like this:
name = local.full_name
Terraform Data Types
Terraform supports multiple data types. The most common ones are:
String
Number
Bool
List
Map
Object
Sample code:
variable "instance_count" {
type = number
default = 2
}
variable "availability_zones" {
type = list(string)
default = ["ap-south-1a", "ap-south-1b"]
}
Output Variables
Output variables show important values after resources are created. They help you share information between modules or quickly see results.
Real life example:
After booking a train, you get a ticket number. That number is like an output. It tells you something important created by the system.
Sample code:
output "instance_ip" {
value = aws_instance.example.public_ip
}
TF_VAR_environment
TF_VAR_environment is a special environment variable. Terraform automatically reads it and passes it to a variable named environment.
Example usage in terminal:
export TF_VAR_environment="dev"
Terraform variable:
variable "environment" {
type = string
}
Now Terraform can use this value without changing code.
Precedence of Variables
When the same variable is defined in multiple places, Terraform follows a fixed priority order. Highest priority wins.
Here is the order from lowest to highest:
Environment variables
terraform.tfvars file
CLI input via -var or -var-file
That means if you pass a value using -var, it overrides everything else.
Example:
terraform apply -var="environment=prod"
Final Thoughts
Terraform variables help you keep your code clean and safe. Variables and locals serve different purposes. Data types make your code predictable. Output values help you see results. Environment variables like TF_VAR_environment make automation easy. Understanding precedence prevents confusion when values change.




