πŸ”— Repo: github.com/Push/terraform-aws-labs/day05

🎯 Goal: Replace hardcoded values with reusable, environment-aware configs β€” no more copy-paste errors!


🧠 Why Variables? The Real Pain Point

Imagine this in a real team:

# ❌ Disaster waiting to happen
tags = { Environment = "dev" }   # S3
tags = { Environment = "stg" }   # VPC ← typo!
tags = { Environment = "dev" }   # EC2

β†’ Your β€œdev” environment has a staging VPC β†’ failed deployments, broken pipelines, and 3 AM pages.

βœ… Variables fix this by letting you define once, reuse everywhere, change in one place.


πŸ“¦ The 3 Variable Types (By Purpose)

Type Analogy Scope When to Use
variable (Input) Function parameters Configurable input env, region, instance_type
locals Local variables (let x = …) Computed, internal-only bucket_name = "${var.app}-${var.env}-logs"
output Function return values Exported results vpc_id, bucket_arn, alb_dns

πŸ’‘ Golden Rule:


✏️ Hands-On: From Hardcoded β†’ Parameterized

Let’s refactor a multi-resource config (S3 + VPC + EC2) using all 3 variable types.

πŸ“ File Structure (Clean & Organized)

day05/
β”œβ”€β”€ main.tf          # Resources
β”œβ”€β”€ variables.tf     # Input variables (env, region)
β”œβ”€β”€ locals.tf        # Computed values (names, tags)
β”œβ”€β”€ outputs.tf       # Results to expose
β”œβ”€β”€ terraform.tfvars # Default values (dev)
└── dev.tfvars       # Dev overrides


1️⃣ variables.tf β€” Input Variables (User-Provided)

# πŸ”Ή variables.tf
variable "env" {
  description = "Deployment environment"
  type        = string
  default     = "dev"
  validation {
    condition     = contains(["dev", "staging", "prod"], var.env)
    error_message = "env must be 'dev', 'staging', or 'prod'."
  }
}

variable "region" {
  description = "AWS region"
  type        = string
  default     = "us-east-1"
}

variable "app" {
  description = "Application name"
  type        = string
  default     = "tech-tutorials-push"
}