🔗 Repo: github.com/Push/terraform-aws-labs/day07

🎯 Goal: Master all 7 type constraints — write configs that fail fast on invalid inputs.

✅ You’ll master:


🧠 Why Type Constraints Matter

❌ var.region = 123 → crashes late (during apply)

type = stringfails early (during plan/validate)

Type constraints = self-documenting, self-validating configs.


📦 Type Constraints Cheat Sheet

Category Type Format Use Case Duplicates? Ordered? Index Access?
Primitive string "hello" Names, IDs, tags
number 42, 3.14 Ports, counts, sizes
bool true, false Flags (e.g., monitoring)
Complex list(<TYPE>) ["a", "b"] Ordered lists (AZs, ports) ✅ ([0])
set(<TYPE>) ["a", "b"] Unique values (regions, tags) ❌ (→ tolist())
map(<TYPE>) {k="v"} Key-value (tags, env vars) Keys ❌ ❌ (→ ["key"])
tuple([T1, T2]) [42, "tcp"] Fixed-position mixed types ✅ ([0])
object({k=T}) {port=443} Structured data (config blocks) Keys ❌ ❌ (["key"])
Special null null Optional/unset values
any 42, "hi" Legacy/fallback (avoid in prod)

💡 Golden Rule:

“Use the most specific type possible — not any.”


✏️ Hands-On: Type Constraints in Action

1️⃣ Primitive Types — The Basics

variables.tf

# 🔹 string (names, regions)
variable "region" {
  type        = string
  default     = "us-east-1"
  description = "AWS region"
}

# 🔹 number (ports, counts)
variable "instance_count" {
  type        = number
  default     = 1
  description = "Number of EC2 instances"
}

# 🔹 bool (flags)
variable "enable_monitoring" {
  type        = bool
  default     = true
  description = "Enable CloudWatch detailed monitoring"
}

main.tf

resource "aws_instance" "app" {
  count         = var.instance_count          # ← number
  ami           = "ami-0c7217cdde317cfec"
  instance_type = "t3.micro"
  monitoring    = var.enable_monitoring      # ← bool

  tags = {
    Region = var.region                      # ← string
  }
}

Validation:

terraform plan -var="region=123" → ❌ Invalid value for "region": string required.