πŸ—οΈ Terraform Local Modules: Custom Reusable Blocks


In modern DevOps and cloud infrastructure, reusability and standardization are key to managing complexity. Terraform provides a powerful feature for this: πŸ‘‰ Local Modules β€” your own custom reusable blocks.

While public modules are downloaded from the Terraform Registry, local modules are created and stored within your own codebase. They encapsulate related resources (like networks, VMs, IAM roles, or storage) into one logical, reusable unit.

This allows teams to reduce duplication, enforce best practices, and accelerate deployments across environments.


πŸ”Ή What Are Terraform Local Modules?

A Terraform Local Module is a self-contained directory that defines a set of resources, variables, and outputs which can be imported and used in multiple Terraform configurations within the same repository or organization.

It’s like creating your own library of infrastructure building blocks.


πŸ’‘ Simple Definition:

Local Modules are reusable Terraform code units stored locally to organize and standardize your infrastructure.


πŸ”Ή Benefits of Using Local Modules

BenefitDescription
ReusabilityWrite once, use across multiple environments.
MaintainabilityCentralize updates to resources (like tags, naming conventions).
ScalabilityModularize infrastructure for teams or environments.
ConsistencyEnforce uniform standards for cloud resources.
SimplicityReduces Terraform file size and improves readability.

πŸ”Ή How Local Modules Work

Root Terraform Configuration

Local Module: /modules/network

Local Module: /modules/compute

Local Module: /modules/security

AWS VPC + Subnets

EC2 Instances + Load Balancer

IAM Roles + Policies

Explanation: The root module references multiple local modules for different components (network, compute, security). Each module has its own variables and outputs, but they work together as one infrastructure.


πŸ”Ή Folder Structure for Local Modules

project/
β”‚
β”œβ”€β”€ main.tf
β”œβ”€β”€ variables.tf
β”œβ”€β”€ outputs.tf
└── modules/
β”œβ”€β”€ vpc/
β”‚ β”œβ”€β”€ main.tf
β”‚ β”œβ”€β”€ variables.tf
β”‚ └── outputs.tf
β”œβ”€β”€ compute/
β”‚ β”œβ”€β”€ main.tf
β”‚ β”œβ”€β”€ variables.tf
β”‚ └── outputs.tf
└── storage/
β”œβ”€β”€ main.tf
β”œβ”€β”€ variables.tf
└── outputs.tf

πŸ”Ή Local Module Anatomy

Each module typically includes:

  • main.tf β†’ Resource definitions
  • variables.tf β†’ Input parameters
  • outputs.tf β†’ Outputs to export values back to root

You can call a local module using:

module "example" {
source = "./modules/example"
}

πŸ”Ή Example 1: AWS VPC Local Module

modules/vpc/main.tf

resource "aws_vpc" "this" {
cidr_block = var.cidr
tags = {
Name = var.name
}
}

modules/vpc/variables.tf

variable "cidr" {}
variable "name" {}

modules/vpc/outputs.tf

output "vpc_id" {
value = aws_vpc.this.id
}

main.tf (root)

provider "aws" {
region = "us-east-1"
}
module "vpc_main" {
source = "./modules/vpc"
cidr = "10.0.0.0/16"
name = "my-main-vpc"
}
output "main_vpc_id" {
value = module.vpc_main.vpc_id
}

βœ… Result: Creates a reusable VPC using a local module. You can reuse it in multiple environments (dev, test, prod) by changing variables only.


πŸ”Ή Example 2: Azure Storage Account Module

modules/storage/main.tf

resource "azurerm_storage_account" "this" {
name = var.name
resource_group_name = var.resource_group_name
location = var.location
account_tier = "Standard"
account_replication_type = "LRS"
}

modules/storage/variables.tf

variable "name" {}
variable "location" {}
variable "resource_group_name" {}

main.tf (root)

provider "azurerm" {
features {}
}
module "storage" {
source = "./modules/storage"
name = "tfstorage001"
location = "East US"
resource_group_name = "tf-rg"
}

βœ… Result: Creates an Azure Storage Account using a local module β€” easily portable across projects.


πŸ”Ή Example 3: GCP Compute Instance Module

modules/compute/main.tf

resource "google_compute_instance" "vm" {
name = var.instance_name
machine_type = var.machine_type
zone = var.zone
boot_disk {
initialize_params {
image = var.image
}
}
network_interface {
network = var.network
access_config {}
}
}

modules/compute/variables.tf

variable "instance_name" {}
variable "machine_type" {}
variable "zone" {}
variable "image" {}
variable "network" {}

main.tf (root)

provider "google" {
project = "gcp-project-demo"
region = "us-central1"
}
module "vm_instance" {
source = "./modules/compute"
instance_name = "tf-vm-1"
machine_type = "e2-medium"
zone = "us-central1-a"
image = "debian-cloud/debian-11"
network = "default"
}

βœ… Result: Deploys a GCP Compute Instance using a custom module β€” reusable for multiple zones or machine types.


πŸ”Ή Advantages of Local Modules

AdvantageDescription
Custom-fit for your OrgDesigned to match your internal standards.
Reusable within RepoUsed across multiple stacks easily.
Version Control ReadyManaged with Git for traceability.
No Internet DependencyWorks offline without Terraform Registry.
Fast IterationInstant testing and updates.

πŸ”Ή Best Practices for Local Modules

  1. βœ… Use Clear Naming Conventions Example: modules/network, modules/security, modules/app

  2. πŸ“¦ Define Variables & Outputs Clearly Avoid hardcoding; make your module flexible.

  3. πŸ”’ Use Version Control (Git) Keep module versions in sync with your code.

  4. 🧩 Keep Modules Focused One module = one purpose (e.g., VPC, EC2, IAM).

  5. 🧱 Document Usage Add README.md with variable descriptions and usage examples.


πŸ”Ή How to Remember This Concept

Use the mnemonic β€œLOCAL”:

LetterMeaning
LLogical structure for your infra
OOrganize reusable components
CCreate consistency
AAvoid duplication
LLeverage modular architecture

πŸ’‘ Memory Trick:

β€œLOCAL Modules keep your infrastructure Local, Organized, Consistent, and Always reusable.”


πŸ”Ή Interview & Exam Preparation

πŸ”Έ Common Interview Questions

  1. Q: What is a local module in Terraform? A: A reusable infrastructure component defined within the same Terraform project.

  2. Q: How do you reference a local module? A:

    module "example" {
    source = "./modules/example"
    }
  3. Q: What’s the difference between local and public modules? A:

    • Local β†’ created and stored locally.
    • Public β†’ downloaded from Terraform Registry.
  4. Q: Can you version-control local modules? A: Yes, by managing them through Git branches or commits.


πŸ”Έ Study Technique β€” β€œR.A.P.I.D.”

StepAction
RRead official Terraform docs
AApply examples manually
PPractice creating modules for each cloud
IInspect open-source module structures
DDocument your own modules

πŸ”Ή Why It’s Important to Learn Local Modules

1. Foundation for Reusable Infrastructure

They form the basis for building enterprise-grade IaC systems.

2. Helps in Terraform Certification Exams

Questions about module structure, usage, and dependency handling are common in HashiCorp Certified: Terraform Associate exam.

3. Accelerates Team Development

Teams can share internal module libraries for rapid cloud provisioning.

4. Supports Multi-Cloud Infrastructure

Local modules can be replicated across AWS, Azure, and GCP.

5. Promotes Best Practices

Encourages clean, DRY (Don’t Repeat Yourself) Terraform code.


πŸ”Ή Common Mistakes to Avoid

MistakeWhy It’s BadSolution
Hardcoding variablesReduces reusabilityUse variables.tf
Not outputting valuesCan’t reference module resultsDefine outputs
Mixing multiple rolesConfusing module logicKeep modules small and focused
Not testing modulesCan cause dependency failuresTest locally with sample configs

πŸ”Ή Real-World Use Cases

  1. Enterprise Infrastructure Templates

    • Standardize AWS VPC, IAM roles, and tagging using local modules.
  2. Multi-Environment Setup

    • Use the same module for Dev, Staging, and Production with different variable values.
  3. Microservice Architecture

    • Each service has its own compute, networking, and storage modules.
  4. Hybrid Cloud Solutions

    • Combine local modules across AWS, GCP, and on-prem resources.

πŸ”Ή Comparison Table: Local vs. Public Modules

FeatureLocal ModulePublic Module
SourceLocal directoryTerraform Registry
Usage ScopeInternal to repoGlobal, open-source
Internet AccessNot requiredRequired
CustomizationFull controlLimited by module design
SecurityPrivatePublicly accessible

πŸ”Ή Summary Table

TopicKey Takeaway
DefinitionLocally defined reusable Terraform components
Syntaxsource = "./modules/<name>"
PurposeDRY, maintainable, reusable IaC
ExamplesAWS VPC, Azure Storage, GCP Compute
MnemonicLOCAL = Logical, Organized, Consistent, Always reusable
Exam TipPractice referencing local modules
BenefitPromotes modular, scalable design

Terraform Local Modules are the backbone of modular infrastructure as code (IaC). They enable developers and DevOps teams to build reusable, organized, and maintainable cloud infrastructure components β€” without rewriting the same code.

By mastering local modules, you can:

  • Simplify your infrastructure management
  • Build reusable architectures
  • Prepare effectively for Terraform certification

πŸ’¬ β€œThink modular β€” build once, deploy everywhere.”

With hands-on practice and consistent naming, you’ll turn your Terraform projects into elegant, scalable blueprints ready for enterprise automation.