What are Variables?

Variables = Reusable values to avoid hardcoding

Benefits: Flexible code, reuse for dev/prod, easy to change


How It Works - 3 Files

File Purpose Example
variables.tf Define structure variable "region" { type = string }
terraform.tfvars Provide values region = "eu-north-1"
main.tf Use variables region = var.region

Flow: Define → Fill → Use


Three Ways to Use Variables

Option 1: All in One File (main.tf)

# Define variables with defaults
variable "region" {
  type    = string
  default = "us-east-1"
}

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

# Use variables
provider "aws" {
  region = var.region
}

resource "aws_instance" "web" {
  instance_type = var.instance_type
  ami           = "ami-12345"
}

Option 2: Two Files (variables.tf + main.tf)

variables.tf

variable "region" {
  type    = string
  default = "us-east-1"  # Default value here
}

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

main.tf

provider "aws" {
  region = var.region
}

resource "aws_instance" "web" {
  instance_type = var.instance_type
  ami           = "ami-12345"
}

Option 3: Three Files (Best Practice)

variables.tf (no defaults)

variable "region" {
  type = string
}

variable "instance_type" {
  type = string
}

terraform.tfvars