Variables = Reusable values to avoid hardcoding
Benefits: Flexible code, reuse for dev/prod, easy to change
| 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
# 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"
}
variable "region" {
type = string
default = "us-east-1" # Default value here
}
variable "instance_type" {
type = string
default = "t3.micro"
}
provider "aws" {
region = var.region
}
resource "aws_instance" "web" {
instance_type = var.instance_type
ami = "ami-12345"
}
variables.tf (no defaults)
variable "region" {
type = string
}
variable "instance_type" {
type = string
}
terraform.tfvars