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 Modules: Reusable Infrastructure Components
In modern DevOps and cloud engineering, reusability is key. Writing repetitive Terraform code for each project quickly becomes inefficient, error-prone, and hard to maintain. Terraform solves this with Modules β self-contained, reusable units of infrastructure configuration.
Think of a module like a βfunctionβ in programming. Just as functions encapsulate logic to be reused, modules encapsulate infrastructure logic (like VPCs, EC2 instances, or Kubernetes clusters) to be reused across environments and teams.
By mastering Terraform Modules, you can build infrastructure thatβs:
- Scalable β one module can power hundreds of deployments
- Consistent β same configuration repeated reliably
- Maintainable β single change cascades everywhere
πΉ What Are Terraform Modules?
A Terraform module is a directory containing one or more .tf
files that define a specific piece of infrastructure.
Every Terraform configuration is technically a module β even the root module in your main working directory.
You can:
- Create local modules (for your project)
- Use public modules from the Terraform Registry
- Publish and version your own modules
π Structure of a Typical Module
my-module/βββ main.tfβββ variables.tfβββ outputs.tfβββ README.md
- main.tf β defines resources
- variables.tf β declares input variables
- outputs.tf β defines outputs that can be consumed by parent modules
- README.md β documents how to use it
πΉ Why Terraform Modules Are Important
Benefit | Description |
---|---|
Reusability | Write once, use across multiple projects and environments. |
Maintainability | Centralize logic; update one place instead of many. |
Consistency | Standardize deployments β reduces configuration drift. |
Collaboration | Teams can share modules internally or via registry. |
Faster Delivery | Speed up infrastructure creation for DevOps pipelines. |
In short: Terraform modules are the foundation of Infrastructure as Code maturity.
πΉ How Terraform Modules Work
Terraform evaluates configurations in layers:
- Root Module: Your main directory (
main.tf
,variables.tf
, etc.) - Child Modules: External or local modules invoked by the root
- Providers: Cloud API connectors (AWS, GCP, Azure, etc.)
- Resources: Actual infrastructure elements created by the provider
When Terraform runs:
- It reads your root configuration
- Loads all modules and merges them into a unified dependency graph
- Executes
plan
andapply
accordingly
πΉ Module Interaction
Explanation:
- The root module orchestrates multiple child modules.
- Each child defines its own resources (like VPC, EC2, S3).
- Providers connect Terraform to the actual cloud infrastructure.
πΉ Core Concepts in Terraform Modules
Concept | Explanation |
---|---|
Input Variables | Parameters to customize module behavior (like AMI ID or region). |
Outputs | Data exposed from a module for reuse (like subnet IDs). |
Source | Path to where the module is located (local, Git, registry). |
Versioning | Allows locking a module to a specific version for stability. |
Composition | Modules can call other modules (nested modules). |
πΉ 3 Unique Examples of Terraform Modules
Example 1: AWS VPC Module
Folder structure:
modules/ βββ vpc/ βββ main.tf βββ variables.tf βββ outputs.tf
π§± vpc/main.tf
resource "aws_vpc" "main" { cidr_block = var.cidr_block tags = { Name = var.vpc_name }}
π₯ vpc/variables.tf
variable "cidr_block" { type = string description = "CIDR block for the VPC"}
variable "vpc_name" { type = string description = "Name tag for the VPC"}
π€ vpc/outputs.tf
output "vpc_id" { value = aws_vpc.main.id}
π§© Root usage
module "network" { source = "./modules/vpc" cidr_block = "10.0.0.0/16" vpc_name = "production-vpc"}
output "vpc_id" { value = module.network.vpc_id}
Run:
terraform initterraform apply
Result: Creates a reusable VPC that can be redeployed for dev, staging, and prod.
Example 2: GCP Storage Module
modules/ βββ gcs_bucket/ βββ main.tf βββ variables.tf βββ outputs.tf
main.tf
resource "google_storage_bucket" "this" { name = var.bucket_name location = var.location storage_class = var.storage_class force_destroy = true}
variables.tf
variable "bucket_name" { type = string }variable "location" { type = string }variable "storage_class" { type = string default = "STANDARD"}
outputs.tf
output "bucket_url" { value = google_storage_bucket.this.url}
Root usage
module "logs" { source = "./modules/gcs_bucket" bucket_name = "app-logs-bucket" location = "US-CENTRAL1" storage_class = "NEARLINE"}
output "logs_bucket_url" { value = module.logs.bucket_url}
Result: Reusable module for creating standardized GCS buckets with uniform policies.
Example 3: Azure Virtual Network Module
modules/ βββ vnet/ βββ main.tf βββ variables.tf βββ outputs.tf
main.tf
resource "azurerm_virtual_network" "vnet" { name = var.name address_space = var.address_space location = var.location resource_group_name = var.resource_group tags = { Environment = var.env }}
variables.tf
variable "name" {}variable "address_space" { type = list(string) }variable "location" {}variable "resource_group" {}variable "env" { default = "dev" }
outputs.tf
output "vnet_id" { value = azurerm_virtual_network.vnet.id}
Root usage
module "networking" { source = "./modules/vnet" name = "corp-vnet" address_space = ["10.1.0.0/16"] location = "East US" resource_group = "rg-main" env = "prod"}
output "vnet_id" { value = module.networking.vnet_id}
Result: Reusable Azure VNet module applicable across environments.
πΉ How to Remember Terraform Modules (Mnemonic)
Use the word βMODULEβ:
Letter | Meaning |
---|---|
M | Make reusable code blocks |
O | Organize infrastructure logically |
D | Define inputs and outputs |
U | Use versioning for consistency |
L | Leverage modules from Registry |
E | Ensure modular design across teams |
Memory Trick:
βA Terraform MODULE makes your infrastructure Modular, Organized, Defined, Used, Leveraged, and Efficient.β
Common interview question:
βWhat are Terraform modules, and how do they help scalability?β
Answer:
Terraform modules are reusable units of configuration that encapsulate resources. They allow code reuse, consistency, and version control across projects, enabling scalable and maintainable infrastructure.
πΉ Why Learning Terraform Modules Is Essential
1. Industry Relevance
Every mature DevOps setup uses modules to structure codebases. Understanding them is mandatory for roles involving Terraform, AWS, or CI/CD automation.
2. Exam & Certification Value
The Terraform Associate Certification (003) exam includes questions on:
- Module usage
- Passing variables
- Source referencing
- Versioning and output dependencies
3. Team Collaboration
Modules promote a βshared infrastructure libraryβ mindset where developers consume pre-approved building blocks, improving security and governance.
4. Reduced Technical Debt
Without modules, every change requires manual updates across multiple configurations. With modules, you fix once and propagate everywhere.
5. Real-World Enterprise Scenarios
- Standardizing VPC, IAM roles, and security groups
- Managing Kubernetes clusters
- Creating multi-region data lake infrastructure
πΉ Best Practices for Terraform Modules
Category | Best Practice |
---|---|
Naming | Use clear, consistent names like vpc , network , app_cluster . |
Documentation | Always include a README with variable descriptions. |
Version Control | Tag and version modules; use version = in root usage. |
Testing | Validate modules using terraform validate and Terratest. |
Outputs | Expose only necessary outputs. |
Composition | Compose smaller modules into larger ones. |
Registry Use | Reuse trusted Terraform Registry modules where possible. |
Security | Limit variables exposing sensitive data (e.g., keys, passwords). |
πΉ Common Pitfalls & Troubleshooting
-
Forgetting to define outputs: Without outputs, parent modules canβt consume child module data.
-
Version mismatches: Lock versions to avoid breaking changes (
version = "~> 1.0"
). -
Hardcoded values: Always use variables for portability.
-
Improper directory structure: Keep each module in its own folder with its variables and outputs.
-
Nested dependency confusion: Document inter-module dependencies to prevent apply order issues.
πΉ Example: Using a Module from Terraform Registry
module "vpc" { source = "terraform-aws-modules/vpc/aws" version = "5.5.1"
name = "prod-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 single_nat_gateway = true
tags = { Terraform = "true" Environment = "production" }}
With one module call, you build an entire AWS VPC setupβwithout writing hundreds of lines.
πΉ Summary Table: Module Concepts
Concept | Description | Example |
---|---|---|
Module | Reusable Terraform code block | module "network" { ... } |
Input Variables | Custom values | variable "region" {} |
Outputs | Exported data | output "vpc_id" |
Source | Module location | "./modules/vpc" or registry URL |
Versioning | Pin module release | version = "~> 1.0" |
Composition | Nesting modules | module.app calls module.network |
πΉ Conclusion
Terraform modules transform your infrastructure from manual scripts into elegant, reusable blueprints.
Whether deploying a multi-region data lake, a Kubernetes cluster, or a scalable web app, modules let you replicate success, enforce standards, and accelerate delivery.
Mastering modules is not just an exam goalβitβs a professional superpower.
βDonβt copy infrastructureβmodularize it. One module today can power a hundred environments tomorrow.β
β Quick Recap
- Terraform Modules = reusable IaC components
- Structure =
main.tf
,variables.tf
,outputs.tf
- Use local or registry sources
- Three examples: AWS VPC, GCP Bucket, Azure VNet
- Mnemonic = MODULE β Modular, Organized, Defined, Used, Leveraged, Efficient