Modules & Reuse
Package and reuse infrastructure with Terraform modules and versioned sources.
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.
# 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]
# ...
} - Explain the difference between the root module and a child module.
- Call a module with input variables and consume one of its outputs.
- Pin a registry module to a major version and explain why.
- Sketch the inputs/outputs of a reusable “database” module.
Cheat Sheet▾
| Concept | Detail |
|---|---|
| Module | Reusable resource bundle |
| Root module | Top-level config |
| Child module | Called via module {} |
source | local / git / registry |
version | Pin for stability |
| Inputs / outputs | Variables / exposed values |
| Reference output | module.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.