What is a Terraform Module? How do you design reusable modules?
Terraform Module
A module is a container for a group of related Terraform resources, allowing you to reuse the same configuration.
Root Module: The directory where you directly run .tf files
Child Module: A module called by another module — can come from local directories, Git repositories, or the Terraform Registry
Module Usage Example
Calling a VPC module:
module "vpc" { source = "terraform-aws-modules/vpc/aws" version = "5.0.0"
name = "my-vpc" cidr = "10.0.0.0/16"
azs = ["us-east-1a", "us-east-1b"] private_subnets = ["10.0.1.0/24", "10.0.2.0/24"] public_subnets = ["10.0.101.0/24", "10.0.102.0/24"]
enable_nat_gateway = true }
Module Design Principles
Single responsibility: Each module manages one logical resource unit (VPC, EKS cluster, RDS)
Appropriate abstraction level: Expose necessary variables, hide implementation details
Input validation: Use validation blocks to verify input values
variable "environment" { type = string validation { condition = contains(["dev", "staging", "prod"], var.environment) error_message = "environment must be dev, staging, or prod" } }
Outputs: Expose values that other modules need (VPC ID, Subnet IDs, etc.)
Module Version Pinning
In production, always pin module version numbers (version = "x.y.z") to avoid accidentally pulling in upstream breaking changes.
✦ AI Mock Interview
Type your answer and get instant AI feedback
Sign in to use AI scoring
