Terraform
Basics & Fundamentals
- Infrastructure as Code (IaC)
- Declarative Syntax in IaC
- Terraform Configuration Files
- Terraform CLI
- Terraform Init
- Terraform Plan
- Terraform Apply
- Terraform Destroy
Providers & Resources
Variables & Outputs
- Input Variables
- Variable Types
- Default Values
- Environment Variables
- Output Values
- Variable Validation
State Management
- Terraform State File
- Terraform Remote State
- Terraform State Locking
- Terraform Drift Detection
- Terraform Refresh
- Terraform Import
Modules (Reusability)
- Terraform Modules
- Terraform Public Modules
- Terraform local modules
- Terraform Module Versioning
- Terraform Nested Modules
Provisioners & Lifecycle
π§© 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
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
Problem | Solution via Nested Modules |
---|---|
Huge Terraform files | Break them into modular, manageable parts |
Repeated code | Reuse common logic |
Difficult testing | Test submodules independently |
Poor scalability | Build hierarchical, reusable structures |
Complex multi-environment setups | Compose modules per environment |
πΉ Advantages of Nested Modules
- Improved Modularity β Each submodule handles a specific task (networking, compute, security).
- Code Reuse β Write once, reuse across projects.
- Ease of Maintenance β Changes in one nested module donβt break others.
- Better Collaboration β Teams can work on separate modules concurrently.
- 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.tfmodules/ βββ 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β π§
Letter | Meaning |
---|---|
N | Nested structure organizes infrastructure |
E | Encapsulate logic into smaller units |
S | Simplify complex environments |
T | Test each module independently |
π‘ Memory Trick:
βIf your infrastructure is a tree, nested modules are its branches.β
πΉ Interview & Exam Preparation Tips
Common Questions
-
Q: What are nested modules in Terraform? A: Modules called inside other modules to build complex, modular infrastructure.
-
Q: Why use nested modules? A: To organize large configurations, reuse logic, and improve scalability.
-
Q: How do nested modules communicate? A: Through variables (inputs) and outputs (exports).
-
Q: Can nested modules be reused independently? A: Yes, each nested module can act as a standalone component.
-
Q: Whatβs the best practice for nested modules? A: Keep them simple, reusable, and parameterized.
π§ Study Technique β βM.O.D.U.L.Eβ
Step | Description |
---|---|
M | Modularize repetitive infrastructure |
O | Organize submodules by purpose |
D | Define clear inputs/outputs |
U | Use consistent naming |
L | Link modules logically |
E | Evaluate with terraform plan |
πΉ Why Itβs Important to Learn Nested Modules
-
Scalability: Enables managing hundreds of resources through structured, reusable components.
-
Maintainability: Teams can easily locate and update specific logic (like networking or security).
-
Reusability: Nested modules can be shared across projects β reducing development time.
-
Collaboration: Developers, DevOps, and SRE teams can work on separate parts simultaneously.
-
Best Practice Compliance: Terraform recommends modular architecture for large-scale infrastructure.
-
Certification Relevance: Terraform Associate Exam often asks how modules interact and how to structure nested modules.
πΉ Best Practices
Best Practice | Description |
---|---|
Keep modules small | Avoid large, monolithic modules |
Use consistent names | Helps identify module roles easily |
Avoid hard-coded values | Always use variables |
Limit module depth | 2-3 levels are ideal |
Reuse across environments | Dev, Stage, Prod via same nested structure |
Document inputs/outputs | Essential for collaboration |
πΉ Common Mistakes to Avoid
Mistake | Why Itβs Problematic | Solution |
---|---|---|
Deep nesting (4+ levels) | Hard to debug and maintain | Limit to 2β3 levels |
Missing outputs | Data not shared between modules | Use output blocks |
Hardcoding variables | Breaks reusability | Use input variables |
No documentation | Confuses team | Maintain README.md per module |
Module circular references | Causes dependency loops | Design flat dependencies |
πΉ Real-World Use Cases
-
Enterprise Infrastructure: Nested modules manage compute, networking, and security layers independently.
-
Multi-Cloud Deployments: Shared nested structures simplify hybrid infrastructure.
-
CI/CD Pipelines: Nested modules integrate easily with automation tools (e.g., Jenkins, GitHub Actions).
-
Compliance Automation: Reusable modules ensure consistent security and governance policies.
πΉ Summary Table
Feature | Terraform Nested Module |
---|---|
Purpose | Structure complex infra into reusable components |
Levels | Root β Child β Nested |
Communication | Through variables.tf and outputs.tf |
Benefits | Modularity, Reusability, Maintainability |
Best Practice | 2β3 nesting levels, documented interfaces |
πΉ Quick Demo Workflow
terraform initterraform validateterraform planterraform 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.