Why variables?
Hardcoding values makes configs brittle:
instance_type = "t3.micro"With a variable you change the value once and reuse it everywhere:
instance_type = var.instance_typeVariable syntax
variable "instance_type" {
type = string
}Access it as var.instance_type.
Variable types
| Type | Example |
|---|---|
| String | type = string |
| Number | type = number |
| Boolean | type = bool |
| List | type = list(string) |
| Map | type = map(string) |
Defaults, description, and validation
variable "instance_type" {
type = string
description = "EC2 instance type"
default = "t3.micro"
validation {
condition = contains(["t3.micro", "t3.small", "t3.medium"], var.instance_type)
error_message = "Valid types are t3.micro, t3.small, and t3.medium."
}
}default— used when no value is supplieddescription— documents intent for teammatesvalidation— rejects invalid values at plan time
Example — variables.tf
variable "bucket_name" {
type = string
}
variable "instance_type" {
type = string
}By convention, declare inputs in variables.tf. Values usually live in terraform.tfvars (next lesson) — keep secrets out of Git.