π Repo: github.com/Push/terraform-aws-labs/day05
π― Goal: Replace hardcoded values with reusable, environment-aware configs β no more copy-paste errors!
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.
| 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:
- Input β What you control
- Locals β What you compute
- Output β What you share
Letβs refactor a multi-resource config (S3 + VPC + EC2) using all 3 variable types.
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
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"
}