Learn Terraform Β· 5/11

Modules: Reusable Infrastructure Components

7 min read

Course: Terraform

Topic: Modules: Reusable Infrastructure Components


πŸ‘‹ Welcome to the Industrial Revolution of Infrastructure!

If you made it this far, you know how to create resources. You are likely feeling powerful. You can spin up an EC2 instance with a few lines of code. But let's be honest for a second: if you had to create 50 identical servers for 50 different environments, would you copy-paste that code block 50 times?

If you answered "Yes," please stop. We care about your sanity. 🧠

Today we are tackling Modules. This is the moment you graduate from "I can write a script" to "I can architect a scalable system."


1. Introduction to Modules: Don't Repeat Yourself (DRY) πŸ—οΈ

The Problem: The "Wall of Text"

Imagine you are building a house. You need a window. You describe the glass, the frame, the handle, and the screws. Now you need another window. Do you describe the glass, frame, handle, and screws again?
In coding, copying and pasting resource blocks leads to massive files (main.tf with 2,000 lines) that are impossible to read, hard to debug, and terrifying to update.

The Concept: What is a Module?

A Module in Terraform is simply a container for multiple resources that are used together. A module consists of a collection of .tf files kept together in a directory.

Technical Definition: A module is a self-contained package of Terraform configurations that encapsulates a specific set of infrastructure resources to provide a reusable abstraction.

πŸ’‘ Interesting Fact: technically, you have already been using modules. The directory where you run terraform apply is called the Root Module. Any module called by the root module is a Child Module.

How it Solves the Problem

Instead of defining the "Window" details 50 times, you define the "Window" once in a separate folder. Then, in your main file, you just say: "Give me a Window here, here, and here."

If you need to change the glass type, you change it in one place, and all 50 windows update automatically. This adheres to the DRY (Don't Repeat Yourself) principle.


2. Consuming Public Modules from the Terraform Registry 🌍

The Problem: Reinventing the Wheel

Let's say you want to build an AWS VPC (Virtual Private Cloud). You need a VPC resource, public subnets, private subnets, internet gateways, route tables, route table associations, and NAT gateways.

Writing that from scratch takes hours and is prone to errors (e.g., forgetting to associate a route table). Why suffer when thousands of engineers have already solved this?

The Solution: The Terraform Registry

The Terraform Registry is a public repository of modules written by the community and official providers (like AWS, Google, Azure).

How to use it

To use a module, you use the module block instead of a resource block.

Scenario: We need a VPC. Instead of writing 15 resource blocks, we use the official AWS VPC module.

hcl
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
}

πŸ” Explanation:

  1. module "vpc": This gives the module instance a local name ("vpc").
  2. source: The most important line. It tells Terraform where to download the code. This address points to the public registry.
  3. version: CRITICAL INDUSTRY PRACTICE. Always pin your version. If you don't, Terraform downloads the latest. If the author releases a breaking change tomorrow, your production pipeline might explode.
  4. Arguments: name, cidr, etc., are input variables defined by the module author.

⚑ Action Step: The init Command

When you add a module, your local Terraform doesn't have the code for it yet. You must run:

bash
terraform init

This downloads the module files into a hidden .terraform/modules directory.


3. Creating Your First Custom Local Module πŸ“¦

The Problem: Company Standards

The public registry is great for generic things (VPCs, K8s clusters), but what about your company's specific needs?

  • "Every S3 bucket must have encryption enabled."
  • "Every web server must have these specific tags."

You can't find a "MyCompany-Specific-Bucket" on the public registry.

The Solution: Local Modules

You create a folder on your computer, put .tf files in it, and reference it using a relative path.

Industry Standard Structure

A clean Terraform project usually looks like this:

text
my-project/
β”œβ”€β”€ main.tf           (Root Module)
β”œβ”€β”€ modules/          (Folder for custom modules)
β”‚   └── web-server/   (Child Module)
β”‚       β”œβ”€β”€ main.tf
β”‚       β”œβ”€β”€ variables.tf
β”‚       └── outputs.tf

Step-by-Step Simulation

Step A: Define the Child Module
Inside modules/web-server/main.tf, we define a simple Nginx server.

hcl
# modules/web-server/main.tf

resource "aws_instance" "app_server" {
  ami           = "ami-0c55b159cbfafe1f0" # Amazon Linux 2 (Example)
  instance_type = "t2.micro"

  tags = {
    Name = "Standard-Web-Server"
    Role = "Production"
  }
}

Step B: Call it from the Root
Inside your root main.tf:

hcl
# main.tf

module "marketing_server" {
  source = "./modules/web-server"
}

module "finance_server" {
  source = "./modules/web-server"
}

Result: You just created two identical servers with standardized tags by writing the resource logic only once!


4. Passing Inputs and Extracting Outputs πŸŽ›οΈ

The Problem: Hardcoded Modules are Useless

Look at the example above. Both servers are t2.micro and have the exact same AMI. What if Marketing needs a bigger server? What if we need to know the IP address of the Finance server to put it in a DNS record?

A module without inputs is like a calculator that only adds 2 + 2. We need it to add X + Y.

The Solution: Variables and Outputs

Think of a module like a Function in programming:

  • Variables = Function Arguments (Input)
  • Resources = Function Logic (Body)
  • Outputs = Return Values (Output)

Practical Implementation

Let's refactor our web-server module to be dynamic.

1. The Inputs (variables.tf inside the module)
We define what the module accepts.

hcl
# modules/web-server/variables.tf

variable "server_size" {
  description = "The EC2 instance type"
  type        = string
  default     = "t2.micro" # Fallback if not specified
}

variable "app_name" {
  description = "Name of the application"
  type        = string
}

2. The Logic (main.tf inside the module)
Update the resource to use these variables.

hcl
# modules/web-server/main.tf

resource "aws_instance" "app_server" {
  ami           = "ami-0c55b159cbfafe1f0" 
  instance_type = var.server_size  # Dynamic size!

  tags = {
    Name = var.app_name            # Dynamic name!
    Role = "Production"
  }
}

3. The Return Values (outputs.tf inside the module)
We define what the module sends back to the root. By default, child module data is hidden (encapsulated). You must explicitly expose it.

hcl
# modules/web-server/outputs.tf

output "instance_ip_addr" {
  value       = aws_instance.app_server.public_ip
  description = "The public IP of the web server"
}

output "instance_id" {
  value = aws_instance.app_server.id
}

4. The Usage (Root main.tf)
Now we pass values in and access values out.

hcl
# main.tf

# 1. Calling the module with inputs
module "marketing_server" {
  source      = "./modules/web-server"
  server_size = "t3.large"    # Marketing needs power!
  app_name    = "Marketing-App"
}

# 2. Using the module's output
resource "aws_eip" "lb" {
  domain   = "vpc"
  # We access the output using: module.<module_name>.<output_name>
  instance = module.marketing_server.instance_id
}

🚨 Industry Best Practices (Read this or suffer)

  1. Pin Versions: When using Public Registry modules, always specify version = "x.y.z". Updates can break your infrastructure.
  2. Relative Paths: When using local modules, start the source path with ./ or ../.
  3. Encapsulation: Don't expose everything. Only create variables for things users need to change, and only output values other resources need to consume.
  4. No Providers in Modules: Generally, do not define provider "aws" {...} inside a child module. Let the root module handle authentication. Child modules inherit providers automatically.

πŸ“š References & Further Reading


Summary: Modules turn your messy "Spaghetti Code" into clean, reusable "Lego Blocks." Use the Registry for standard infrastructure (VPC, RDS), and write Local Modules for your company's specific patterns. Now, go refactor your code! 🧹✨

Challenge

Challenge: Create and Use a Local Terraform Module

Your task is to build a reusable local Terraform module for deploying a standardized S3 bucket configured for static website hosting. You will then call this module from your root main.tf file.

Simulate the following directory structure within the single editor window using comments as file dividers.

stylus
my-project/
β”œβ”€β”€ main.tf
└── modules/
    └── s3_static_site/
        β”œβ”€β”€ main.tf
        β”œβ”€β”€ variables.tf
        └── outputs.tf

Module (s3_static_site) Requirements:

  1. Inputs (variables.tf): The module must accept two input variables:

    • bucket_name: A variable of type string for the S3 bucket's unique name.
    • tags: A variable of type map(string) to apply common tags to the bucket.
  2. Resources (main.tf): The module must define the following AWS resources:

    • An aws_s3_bucket resource that uses the bucket_name and tags input variables.
    • An aws_s3_bucket_website_configuration resource associated with the bucket, configuring index_document to index.html.
    • An aws_s3_bucket_public_access_block resource that sets block_public_acls and block_public_policy to false, and ignore_public_acls and restrict_public_buckets to false to allow public access for the website.
  3. Outputs (outputs.tf): The module must expose two values:

    • bucket_arn: The ARN of the created S3 bucket.
    • website_endpoint: The website endpoint of the S3 bucket.

Root Module (main.tf) Requirements:

  1. Define a module block with the local name personal_blog.
  2. Use the correct relative source path to reference your local s3_static_site module.
  3. Pass the following values to the module:
    • bucket_name: my-unique-static-blog-bucket
    • tags: A map containing {"ManagedBy" = "Terraform", "Project" = "Blog"}

Expected result

Your final code should be structured into the four commented sections provided in the initial code.

  • modules/s3_static_site/variables.tf: This section should contain two variable blocks, one for bucket_name and one for tags, each defined with the correct type.
  • modules/s3_static_site/main.tf: This section should contain three resource blocks: aws_s3_bucket, aws_s3_bucket_website_configuration, and aws_s3_bucket_public_access_block. The resource attributes should correctly reference the input variables (e.g., var.bucket_name).
  • modules/s3_static_site/outputs.tf: This section should contain two output blocks for bucket_arn and website_endpoint. Their value attributes should reference the appropriate attributes from the resources created in the module's main.tf.
  • main.tf (Root Module): This section must contain a single module "personal_blog" block. The source attribute must be the correct relative path ("./modules/s3_static_site"). The block must pass the specified bucket_name string and tags map as arguments.
hcl

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.