Modules & Reuse

💤0
Lv 10 XP
← 📜 Infrastructure as Code · Terraform

Modules & Reuse

Intermediate ⭐ 80 XP ⏱ 18 min #terraform#modules#reuse

Package and reuse infrastructure with Terraform modules and versioned sources.

📖Theory

A module is a reusable, parameterized bundle of resources. Any folder with .tf files is a module; the top level is the root module, and it calls child modules. Modules take input variables and expose outputs, so the same module produces dev, staging, and prod with different inputs.

Source modules from a local path, a git URL, or the Terraform Registry — and pin a version for stability. Good modules are small, focused (a “vpc” module, a “database” module), and have clear inputs/outputs.

🌍Real-World Example
# Call a registry module with pinned version
module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "~> 5.0"

  name = "prod-vpc"
  cidr = "10.0.0.0/16"
  azs  = ["eu-west-1a", "eu-west-1b"]
}

# Use the module's output
resource "aws_instance" "app" {
  subnet_id = module.vpc.private_subnets[0]
  # ...
}
✍️Hands-On Exercise
  1. Explain the difference between the root module and a child module.
  2. Call a module with input variables and consume one of its outputs.
  3. Pin a registry module to a major version and explain why.
  4. Sketch the inputs/outputs of a reusable “database” module.
🧾Cheat Sheet
ConceptDetail
ModuleReusable resource bundle
Root moduleTop-level config
Child moduleCalled via module {}
sourcelocal / git / registry
versionPin for stability
Inputs / outputsVariables / exposed values
Reference outputmodule.name.output
💬Common Interview Questions
What is a Terraform module and why use one?

A reusable, parameterized collection of resources. Modules eliminate copy-paste, enforce standards, and let one definition serve many environments via different inputs.

Why pin module (and provider) versions?

To get reproducible builds. Floating versions can pull a release that changes behavior unexpectedly, causing drift or breakage across environments.

📚Official Documentation

📝 My notes on this topic

Auto-saves as you type