Table of Contents
Terraform Variable Types
Terraform has four ways to handle dynamic values: input variables, output values, local values, and environment variables.
Input Variables
Declared with variable blocks, used to parameterize configurations:
variable "instance_type" {
type = string
default = "t3.micro"
description = "EC2 instance type"
validation {
condition = contains(["t3.micro", "t3.small", "t3.medium"], var.instance_type)
error_message = "Instance type must be t3.micro, t3.small, or t3.medium."
}
}
Setting Variable Values (Priority Order)
-varflag (highest):terraform apply -var="instance_type=t3.small"-var-file:terraform apply -var-file="prod.tfvars"*.auto.tfvarsfiles (alphabetical order)terraform.tfvarsfileTF_VAR_environment variables:export TF_VAR_instance_type=t3.small- Default value in variable declaration
- Interactive prompt (lowest)
Complex Types
variable "tags" {
type = map(string)
default = {
Environment = "dev"
Team = "platform"
}
}
variable "subnets" {
type = list(object({
cidr = string
az = string
}))
}
Output Values
Expose information from your configuration:
output "instance_ip" {
value = aws_instance.web.public_ip
description = "Public IP of the web server"
}
output "db_password" {
value = random_password.db.result
sensitive = true
}
Access module outputs: module.networking.vpc_id
Local Values
Computed values for use within a module — reduce repetition:
locals {
common_tags = {
Project = var.project
Environment = var.environment
ManagedBy = "terraform"
}
name_prefix = "${var.project}-${var.environment}"
}
resource "aws_instance" "web" {
tags = merge(local.common_tags, { Name = "${local.name_prefix}-web" })
}
When to Use Each
| Type | Use When |
|---|---|
| Input variable | Value differs between environments or users |
| Output | Exposing values to parent modules or CLI |
| Local | Computed values used multiple times in same module |
| Environment | CI/CD pipelines, secrets, overrides |
Learn More
- Terraform for Beginners Course — hands-on variable labs
- Terraform By Example Book — real-world patterns
- Terraform Cheat Sheet — quick command reference



