🧩 Terraform Nested Modules: Build Complex Infrastructure with Modularity


As your infrastructure grows, so does the complexity of managing it. Defining all your resources in one large Terraform configuration file quickly becomes hard to maintain, test, and reuse.

This is where Terraform Nested Modules come into play β€” a powerful way to organize, scale, and simplify your infrastructure as code (IaC).


πŸ’‘ Simple Definition

Terraform Nested Modules are modules inside other modules that allow you to structure complex infrastructure into smaller, reusable, and organized building blocks.

Think of it like a folder structure:

  • A root module acts as the entry point
  • It can call multiple child modules
  • Those child modules can call submodules (nested modules) for deeper modularity

πŸ”Ή Example Analogy

Imagine building a car:

  • The root module = entire car
  • The nested modules = engine, wheels, electronics
  • Each subcomponent (like the engine) has its own modules (fuel system, pistons, cooling system)

This layered design ensures organization, reusability, and maintainability.


πŸ”Ή Terraform Module Hierarchy

Root Module

Network Module

Compute Module

Storage Module

Subnet Nested Module

SecurityGroup Nested Module

Instance Nested Module

S3 Nested Module

Explanation: The Root Module (main.tf) calls Network, Compute, and Storage modules. Each of those modules further calls nested modules (e.g., Subnet, Security Group, Instance).


πŸ”Ή Why Nested Modules Are Important

ProblemSolution via Nested Modules
Huge Terraform filesBreak them into modular, manageable parts
Repeated codeReuse common logic
Difficult testingTest submodules independently
Poor scalabilityBuild hierarchical, reusable structures
Complex multi-environment setupsCompose modules per environment

πŸ”Ή Advantages of Nested Modules

  1. Improved Modularity – Each submodule handles a specific task (networking, compute, security).
  2. Code Reuse – Write once, reuse across projects.
  3. Ease of Maintenance – Changes in one nested module don’t break others.
  4. Better Collaboration – Teams can work on separate modules concurrently.
  5. Consistency – Enforces uniform patterns across environments.

πŸ”Ή Structure of Nested Modules

A typical Terraform project with nested modules looks like this:

terraform-project/
β”‚
β”œβ”€β”€ main.tf
β”œβ”€β”€ variables.tf
β”œβ”€β”€ outputs.tf
β”‚
└── modules/
β”œβ”€β”€ network/
β”‚ β”œβ”€β”€ main.tf
β”‚ β”œβ”€β”€ variables.tf
β”‚ β”œβ”€β”€ outputs.tf
β”‚ └── submodules/
β”‚ β”œβ”€β”€ subnet/
β”‚ β”‚ β”œβ”€β”€ main.tf
β”‚ β”‚ └── variables.tf
β”‚ └── security-group/
β”‚ β”œβ”€β”€ main.tf
β”‚ └── variables.tf
β”‚
β”œβ”€β”€ compute/
β”‚ β”œβ”€β”€ main.tf
β”‚ └── variables.tf
β”‚
└── storage/
β”œβ”€β”€ main.tf
└── variables.tf

πŸ”Ή Example 1: AWS VPC with Nested Modules

This example demonstrates a root module calling a network module, which then calls submodules for subnets and security groups.

πŸ“ Folder Structure

main.tf
modules/
└── network/
β”œβ”€β”€ main.tf
β”œβ”€β”€ variables.tf
β”œβ”€β”€ outputs.tf
└── submodules/
β”œβ”€β”€ subnet/
β”‚ └── main.tf
└── security-group/
└── main.tf

βœ… main.tf (Root Module)

provider "aws" {
region = "us-east-1"
}
module "network" {
source = "./modules/network"
vpc_cidr = "10.0.0.0/16"
}

βœ… modules/network/main.tf

resource "aws_vpc" "main" {
cidr_block = var.vpc_cidr
}
module "subnet" {
source = "./submodules/subnet"
vpc_id = aws_vpc.main.id
}
module "security_group" {
source = "./submodules/security-group"
vpc_id = aws_vpc.main.id
}
output "vpc_id" {
value = aws_vpc.main.id
}

βœ… modules/network/submodules/subnet/main.tf

resource "aws_subnet" "public" {
vpc_id = var.vpc_id
cidr_block = "10.0.1.0/24"
map_public_ip_on_launch = true
}

βœ… modules/network/submodules/security-group/main.tf

resource "aws_security_group" "allow_ssh" {
vpc_id = var.vpc_id
name = "allow_ssh"
ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}

Result: This nested structure builds a complete VPC setup with subnets and security groups.


πŸ”Ή Example 2: Azure Nested Module – Resource Group β†’ VNet β†’ Subnet

βœ… main.tf

provider "azurerm" {
features {}
}
module "network" {
source = "./modules/network"
resource_group = "tf-rg"
location = "East US"
}

βœ… modules/network/main.tf

resource "azurerm_resource_group" "rg" {
name = var.resource_group
location = var.location
}
module "vnet" {
source = "./submodules/vnet"
rg_name = azurerm_resource_group.rg.name
location = var.location
}

βœ… modules/network/submodules/vnet/main.tf

resource "azurerm_virtual_network" "vnet" {
name = "tf-vnet"
address_space = ["10.1.0.0/16"]
location = var.location
resource_group_name = var.rg_name
}
module "subnet" {
source = "./subnet"
vnet_name = azurerm_virtual_network.vnet.name
rg_name = var.rg_name
}

βœ… modules/network/submodules/vnet/subnet/main.tf

resource "azurerm_subnet" "subnet" {
name = "tf-subnet"
resource_group_name = var.rg_name
virtual_network_name = var.vnet_name
address_prefixes = ["10.1.1.0/24"]
}

Result: This nested structure provisions an Azure Resource Group β†’ Virtual Network β†’ Subnet hierarchy seamlessly.


πŸ”Ή Example 3: GCP Nested Modules – Project β†’ Network β†’ Firewall

βœ… main.tf

provider "google" {
project = "gcp-demo"
region = "us-central1"
}
module "project_setup" {
source = "./modules/project"
project_name = "tf-nested-demo"
}

βœ… modules/project/main.tf

module "network" {
source = "./submodules/network"
project = var.project_name
}

βœ… modules/project/submodules/network/main.tf

resource "google_compute_network" "vpc_network" {
name = "tf-network"
}
module "firewall" {
source = "./firewall"
network = google_compute_network.vpc_network.name
}

βœ… modules/project/submodules/network/firewall/main.tf

resource "google_compute_firewall" "allow_ssh" {
name = "allow-ssh"
network = var.network
allow {
protocol = "tcp"
ports = ["22"]
}
source_ranges = ["0.0.0.0/0"]
}

Result: Nested modules create a complete GCP project network with firewall configurations.


πŸ”Ή How to Remember Nested Modules (Mnemonic)

Use the mnemonic β€œNEST” 🧠

LetterMeaning
NNested structure organizes infrastructure
EEncapsulate logic into smaller units
SSimplify complex environments
TTest each module independently

πŸ’‘ Memory Trick:

β€œIf your infrastructure is a tree, nested modules are its branches.”


πŸ”Ή Interview & Exam Preparation Tips

Common Questions

  1. Q: What are nested modules in Terraform? A: Modules called inside other modules to build complex, modular infrastructure.

  2. Q: Why use nested modules? A: To organize large configurations, reuse logic, and improve scalability.

  3. Q: How do nested modules communicate? A: Through variables (inputs) and outputs (exports).

  4. Q: Can nested modules be reused independently? A: Yes, each nested module can act as a standalone component.

  5. Q: What’s the best practice for nested modules? A: Keep them simple, reusable, and parameterized.


🧠 Study Technique β€” β€œM.O.D.U.L.E”

StepDescription
MModularize repetitive infrastructure
OOrganize submodules by purpose
DDefine clear inputs/outputs
UUse consistent naming
LLink modules logically
EEvaluate with terraform plan

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

  1. Scalability: Enables managing hundreds of resources through structured, reusable components.

  2. Maintainability: Teams can easily locate and update specific logic (like networking or security).

  3. Reusability: Nested modules can be shared across projects β€” reducing development time.

  4. Collaboration: Developers, DevOps, and SRE teams can work on separate parts simultaneously.

  5. Best Practice Compliance: Terraform recommends modular architecture for large-scale infrastructure.

  6. Certification Relevance: Terraform Associate Exam often asks how modules interact and how to structure nested modules.


πŸ”Ή Best Practices

Best PracticeDescription
Keep modules smallAvoid large, monolithic modules
Use consistent namesHelps identify module roles easily
Avoid hard-coded valuesAlways use variables
Limit module depth2-3 levels are ideal
Reuse across environmentsDev, Stage, Prod via same nested structure
Document inputs/outputsEssential for collaboration

πŸ”Ή Common Mistakes to Avoid

MistakeWhy It’s ProblematicSolution
Deep nesting (4+ levels)Hard to debug and maintainLimit to 2–3 levels
Missing outputsData not shared between modulesUse output blocks
Hardcoding variablesBreaks reusabilityUse input variables
No documentationConfuses teamMaintain README.md per module
Module circular referencesCauses dependency loopsDesign flat dependencies

πŸ”Ή Real-World Use Cases

  1. Enterprise Infrastructure: Nested modules manage compute, networking, and security layers independently.

  2. Multi-Cloud Deployments: Shared nested structures simplify hybrid infrastructure.

  3. CI/CD Pipelines: Nested modules integrate easily with automation tools (e.g., Jenkins, GitHub Actions).

  4. Compliance Automation: Reusable modules ensure consistent security and governance policies.


πŸ”Ή Summary Table

FeatureTerraform Nested Module
PurposeStructure complex infra into reusable components
LevelsRoot β†’ Child β†’ Nested
CommunicationThrough variables.tf and outputs.tf
BenefitsModularity, Reusability, Maintainability
Best Practice2–3 nesting levels, documented interfaces

πŸ”Ή Quick Demo Workflow

Terminal window
terraform init
terraform validate
terraform plan
terraform apply

πŸ”Ή Conclusion

Terraform Nested Modules are the cornerstone of building modular, maintainable, and reusable infrastructure-as-code architectures. They bring structure, scalability, and collaboration to complex environments β€” turning thousands of lines of code into elegant, manageable layers.

πŸ’¬ β€œNested modules don’t just build infrastructure β€” they build organization and clarity.”

Mastering this concept is crucial for:

  • Enterprise DevOps Engineers
  • Terraform Certification candidates
  • Teams managing multi-environment cloud systems

By following best practices, using semantic structure, and applying consistent naming conventions, you’ll design Terraform projects that scale seamlessly and remain easy to understand β€” even years later.