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)

  1. -var flag (highest): terraform apply -var="instance_type=t3.small"
  2. -var-file: terraform apply -var-file="prod.tfvars"
  3. *.auto.tfvars files (alphabetical order)
  4. terraform.tfvars file
  5. TF_VAR_ environment variables: export TF_VAR_instance_type=t3.small
  6. Default value in variable declaration
  7. 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

TypeUse When
Input variableValue differs between environments or users
OutputExposing values to parent modules or CLI
LocalComputed values used multiple times in same module
EnvironmentCI/CD pipelines, secrets, overrides

Learn More