Modules

Objective

Understand the basics of Terraform modules.

Overview

Modules are a Terraform construct that allows the grouping of Terraform components for reusability. Similar to a function in other languages they allow for inputs and outputs much like a functions arguments and returns. Modules are contained either in a folder or in the Terraform Registry. Module declarations contain three parts, the module keyword, a name, and a configuration block. The source parameter is required in the configuration block.

module "name" {
  source = "./folder"
}

Lab

In this lab we will create a module of our existing resource and call it in our project.

Create a New Module

Execute

mkdir pet-name
touch pet-name/{main,outputs,variables}.tf

Edit pet-name/main.tf

resource "random_pet" "pet" {}

Edit pet-name/outputs.tf

output "name" {
  value = random_pet.pet.id
}

Call The Module

Edit main.tf

module "pet_name" {
  source = "./pet-name"
}

Add Another Output

Edit outputs.tf

output "module" {
  value = module.pet_name.name
}

Plan

Execute

terraform plan

Apply

Execute

terraform apply

Review

In this section we created a new module and added some code. We used the outputs of that module and passed it to an output in our root module.

Additional Reading