Understanding Variable Types & Validation in Terraform

DevOps Enginner
Terraform variables are not just inputs — they are contracts that define what kind of data your infrastructure accepts. Proper typing and validation help prevent misconfiguration, enforce standards, and make your IaC production-ready.
1. Basic Types
Terraform supports three primitive types:
string – Text values
Used for names, regions, IDs, etc.
variable "environment" {
type = string
}
number – Integers or floats
Used for ports, counts, sizes.
variable "instance_count" {
type = number
}
bool – true / false
Used for feature flags.
variable "enable_backup" {
type = bool
}
2. Collection Types
list(type) – Ordered values
variable "subnets" {
type = list(string)
}
set(type) – Unique, unordered values
variable "allowed_ips" {
type = set(string)
}
map(type) – Key-value pairs
variable "instance_types" {
type = map(string)
}
3. Structural Types
tuple – Fixed position & types
variable "server_meta" {
type = tuple([string, number, bool])
}
object – Real-world structured config
variable "ec2_config" {
type = object({
name = string
cpu = number
public = bool
tags = map(string)
})
}
4. Type Validation (Constraints)
Validation ensures business rules, not just data types.
Example: Environment enforcement
variable "env" {
type = string
validation {
condition = contains(["dev", "stage", "prod"], var.env)
error_message = "Environment must be dev, stage, or prod."
}
}
Port range check:
variable "app_port" {
type = number
validation {
condition = var.app_port > 0 && var.app_port <= 65535
error_message = "Port must be between 1 and 65535."
}
}
CIDR validation:
variable "vpc_cidr" {
type = string
validation {
condition = can(cidrnetmask(var.vpc_cidr))
error_message = "Invalid CIDR block."
}
}
5. Why Type Constraints Matter
They help in:
Environment-specific configuration control
Resource sizing enforcement
Tag standardization
Network & security policy validation
Preventing invalid Terraform plans before deployment
6. Best Practices
Always define variable types (never leave implicit)
Use
objectfor complex infra configsValidate critical inputs (CIDR, ports, env, sizes)
Prefer
setfor unique values (SG rules, IPs)Write meaningful error messages
Document every variable with
descriptionUse type conversion when required:
tostring(),tonumber(),tolist()
Terraform types + validation turn your infrastructure into a strongly-typed system, making it safer, predictable, and production-ready.
They act like guardrails that stop broken infrastructure before it even reaches the cloud.
Github Link:- https://github.com/sidharthhhh/terraform/tree/main/day7
For more reference:- https://youtu.be/NjL9lwUfw-4?si=DAKltdtQQ3efqtG7



