Day 04 Advanced Patterns

Modules: Reusable Infrastructure

Extract configurations into modules, use the Terraform Registry, and structure a multi-environment repo.

~1 hour Hands-on Precision AI Academy

Today's Objective

Learn the core concepts of Modules: Reusable Infrastructure and apply them in practical exercises.

01

Creating a Module

Directory Structure
Directory Structure
infrastructure/
├── main.tf
├── variables.tf
├── outputs.tf
└── modules/
    └── web-server/
        ├── main.tf       ← module resources
        ├── variables.tf  ← module inputs
        └── outputs.tf    ← module outputs
modules/web-server/variables.tf
modules/web-server/variables.tf
variable "instance_type" {
  type    = string
  default = "t3.micro"
}

variable "name" {
  type = string
}

variable "subnet_id" {
  type = string
}

variable "security_group_ids" {
  type = list(string)
}
Root main.tf — using the module
Root main.tf — using the module
module "web" {
  source = "./modules/web-server"

  name               = "production-web"
  instance_type      = "t3.small"
  subnet_id          = aws_subnet.public.id
  security_group_ids = [aws_security_group.web.id]
}

# Public registry modules
module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "5.1.0"

  name = "my-vpc"
  cidr = "10.0.0.0/16"
  azs  = ["us-east-1a", "us-east-1b"]
}
💡
The Terraform Registry (registry.terraform.io) has community modules for everything: VPCs, EKS clusters, RDS databases. Using terraform-aws-modules/vpc/aws is better than writing your own VPC from scratch — it handles edge cases you haven't thought of yet.

Supporting References & Reading

Go deeper with these external resources.

Terraform Docs
Modules: Reusable Infrastructure Official HashiCorp Terraform documentation.
YouTube
Modules: Reusable Infrastructure Terraform tutorials on YouTube
MDN
MDN Web Docs Comprehensive web technology reference

Day 4 Checkpoint

Before moving on, confirm understanding of these key concepts:

Continue To Day 5
Day 5 of the Terraform in 5 Days course