CUSTOMISED
Expert-led training for your team
Dismiss
An Introduction to Terraform Modules for Reusable Composable Infrastructure 

28 August 2023

An Introduction to Terraform Modules for Reusable Composable Infrastructure 

Terraform modules are one of the key features that make Terraform a powerful infrastructure as code tool. Modules allow you to encapsulate reusable Terraform configurations and share them. This enables implementing infrastructure patterns for composability and reusability.

In this beginner's guide, we'll cover the basics of Terraform modules including when and how to use them. We'll look at creating, consuming, and publishing modules to simplify infrastructure provisioning.

This material can be form on our Terraform Training Course. The perfect solution whether you are considering training as an individual or as a team. 

What are Terraform Modules?

Terraform modules are self-contained packages of Terraform configurations that define a set of infrastructure resources.

Modules encapsulate common infrastructure patterns like networks, load balancers, and databases so they can be reused. Modules expose:

  • Input variables - For customizing the module behavior
  • Output values - That other resources can reference

Using modules makes it easier to reuse and share Terraform code. Teams can collaborate around centralized modules for consistency and compliance.

Some examples of common infrastructure that can be modularized:

  • VPC networks
  • EC2 instances
  • Database clusters like RDS
  • Load balancers
  • Kubernetes clusters
  • Storage like S3 buckets

Almost any Terraform configuration can be packaged as a module for reuse.

Why Use Terraform Modules?

Terraform modules provide these key advantages:

  • Reusability - Encapsulate infrastructure logic into reusable components
  • Encapsulation - Treat infrastructure as a black box hiding complexity
  • Abstraction - Work at a higher level focused on components
  • Consistency - Standardize and distribute configurations
  • Organization - Structure large configurations using modules as building blocks
  • Shareability - Share modules through public and private registries

Using modules makes Terraform configurations:

  • Composable - Infrastructure can be assembled from modules
  • Flexible - Modules parameters customize functionality
  • Maintainable - Modules isolate and abstract complexity

Overall, modules help teams scale Terraform usage by making infrastructure patterns reusable, encapsulated, and composable.

Creating Terraform Modules

Terraform modules are created by encapsulating related infrastructure resources and exposing input and output variables.

For example, we can create a reusable module for an AWS VPC network:


# vpc.tf

variable "vpc_cidr" {
  default = "10.0.0.0/16" 
}

resource "aws_vpc" "main" {
  cidr_block = var.vpc_cidr
  
  # Other VPC properties
}

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

This defines a module that creates a VPC and exposes the ID as an output.

To use variables and outputs, modules behave much like any other Terraform configuration. Input variables parameterize the module behavior while output values expose information other resources need to reference the module.

Some best practices for module development:

  • Encapsulate a cohesive unit of infrastructure
  • Expose descriptive inputs and outputs for usability
  • Use semantic versioning for releases
  • Write documentation on usage and version changes
  • Follow code commenting and formatting standards

With a module defined, let's look at how to use modules.

Consuming Terraform Modules

To use a Terraform module, declare a module block referencing the source location and pass in values for required input variables:

 
# modules.tf

module "vpc" {
  source = "./vpc"
  
  vpc_cidr = "10.123.0.0/16"
}

This consumes the VPC module by setting the input variable and making the output values available.

Additional practices when using modules:

  • Initialize modules with terraform init
  • Understand module inputs and outputs
  • Reference module outputs in other resources
  • Run terraform plan to verify changes from modules
  • Reuse modules and pass different parameters

Modules enable reusable infrastructure patterns and simplify configurations by encapsulating complexity.

Publishing Terraform Modules

After creating useful Terraform modules, they can be shared and distributed easily:

  • Terraform Registry - Public modules at registry.terraform.io
  • Private Registry - Host your own module registry
  • Git - Share modules directly from Git repositories

Publishing modules enables discovering, using, and collaborating around infrastructure patterns. Some tips:

  • Follow module publishing best practices
  • Use semantic versions like v1.0.0
  • IncludeREADME documentation on usage and inputs/outputs
  • Automate module testing and releases

Let's look at using published modules from the public Terraform Registry.

Using Terraform Registry Modules

The Terraform Registry provides a discovery and collaboration platform for modules. It hosts thousands of reusable modules contributed by the community.

Using registry modules is easy. Reference the module source using the registry hostname:


module "aws_vpc" {
  source = "terraform-aws-modules/vpc/aws"

  version = "3.19.0"
  
  # ...
}  

This pulls the module directly from the registry instead of locally.

Some key benefits of leveraging registry modules:

  • Eliminates reinventing common infrastructure
  • Speeds up project velocity by composing proven code
  • Enables collaboration around modules
  • Discovers best practices encapsulated in modules

Publishing and consuming modules from the public Terraform Registry helps teams share infrastructure patterns and accelerate provisioning.

Example: Reusable AWS VPC Module

To demonstrate creating and using a real-world module, we'll walk through packaging a customizable VPC network module.

Our module will create an AWS VPC with the following:

  • VPC with CIDR block input
  • Public and private subnets across AZs
  • Internet gateway for public subnet routing
  • Route table associations

Create the Module

First, we encapsulate the VPC and related resources into a Terraform configuration module:


# vpc.tf

variable "vpc_cidr" {
  default = "10.0.0.0/16"
}

resource "aws_vpc" "main" {
  cidr_block = var.vpc_cidr
  # Other properties
}

# Public subnets
resource "aws_subnet" "public" {
  vpc_id = aws_vpc.main.id
  cidr_block = "10.0.1.0/24"

  # ...
}

# Private subnets  
resource "aws_subnet" "private" {
  vpc_id = aws_vpc.main.id
  cidr_block = "10.0.2.0/24"

  #...
}

# Internet Gateway
resource "aws_internet_gateway" "main" {
  vpc_id = aws_vpc.main.id

  #...
}

# Route tables  
resource "aws_route_table" "public" {
  vpc_id = aws_vpc.main.id

  # ...
}

# Outputs
output "vpc_id" {
  value = aws_vpc.main.id
}

This module creates the VPC, subnets, internet gateway and route tables.

Consuming the Module

We can now consume the module from a root Terraform configuration:


module "vpc" {
  source = "./vpc"

  vpc_cidr = "10.123.0.0/16"
}

output "vpc_id" {
  value = module.vpc.vpc_id 
}

This declares the module usage, passes a custom VPC CIDR, and exports the VPC ID output.

By encapsulating common infrastructure in modules, we can quickly reuse these patterns for faster and more flexible provisioning. Modules allow composing together infrastructure components in a declarative and reusable way.

Conclusion

Terraform modules are a powerful paradigm for managing infrastructure as code. By encapsulating and parameterizing common infrastructure patterns, modules make configurations:

  • Reusable - Share and reuse proven infrastructure code
  • Composable - Assemble systems by combining modules
  • Encapsulated - Hide complexity behind simple interfaces
  • Maintainable - Upgrade modules without changing usage
  • Discoverable - Leverage public modules from the Terraform Registry

Modules promote reusable, declarative infrastructure definition. Mastering modules will help you and your team scale Terraform usage for managing infrastructure as code.

Next Steps

In today's dynamic infrastructure environment, Terraform is an invaluable tool for operations teams and developers alike. Its capabilities for declaratively defining, provisioning, and managing infrastructure as code can drive more efficient, collaborative infrastructure management.

Whether you're just starting out with infrastructure-as-code or looking to improve an existing Terraform implementation, our Terraform training courses at JBI Training can help you master this powerful platform. So why wait? Embrace the power of infrastructure-as-code and transform your infrastructure workflows today.

Start your learning journey today with the Terraform courses at JB International and unlock the potential of infrastructure-as-code at your fingertips, including:

Terraform: Learn how to use Terraform to build, change, and version infrastructure safely and efficiently. 

DevOps: Gain comprehensive DevOps Skills - with AWS, Docker, Ansible and Terraform

To dive deeper into Terraform modules:

Terraform modules unlock managing infrastructure as composable building blocks. They enable sharing proven infrastructure code to accelerate provisioning across teams and the wider Terraform community.

About the author: Daniel West
Tech Blogger & Researcher for JBI Training

CONTACT
+44 (0)20 8446 7555

[email protected]

SHARE

 

Copyright © 2024 JBI Training. All Rights Reserved.
JB International Training Ltd  -  Company Registration Number: 08458005
Registered Address: Wohl Enterprise Hub, 2B Redbourne Avenue, London, N3 2BS

Modern Slavery Statement & Corporate Policies | Terms & Conditions | Contact Us

POPULAR

Rust training course                                                                          React training course

Threat modelling training course   Python for data analysts training course

Power BI training course                                   Machine Learning training course

Spring Boot Microservices training course              Terraform training course

Kubernetes training course                                                            C++ training course

Power Automate training course                               Clean Code training course