Posted on Leave a comment

Create and use terraform modules

Terraform modules are useful in various scenarios when working with Infrastructure as Code (IaC) using Terraform. Modules provide a way to encapsulate and reuse infrastructure configurations, making it easier to manage and scale your infrastructure code.

Every Terraform configuration has at least one module, known as its root module, which consists of the resources defined in the .tf files in the main working directory.

A module can call other modules, which lets you include the child module’s resources into the configuration in a concise way. Modules can also be called multiple times, either within the same configuration or in separate configurations, allowing resource configurations to be packaged and re-used.

Lets take a look how we can create and use terraform modules. The first thing that you will need to do is to structure your code somehow. A most common way to create a structure would be to create folders and name them after your module. For example if you have to deploy a cloud solution with multiple components you could create a module for each component. In my structure you can find two folders with the name module1 and module2. The module2 will call module1 to reuse its code inside the terraform configuration.

The module1 folder contains the files that are shown. file will be used to fetch all the necessary providers. In my example I use the random provider to generate a random string with terraform.

terraform {
  required_providers {
    random = {
      source  = "hashicorp/random"
      version = "~> 3.5"
} will call the random code to generate the string.

resource "random_string" "module1_random" {
  length           = 16
  special          = true
  override_special = "/@£$"

And finally the file will be used to mark the string as an output and print it in the console.

The module2 folder will only include a which will call module1. In order to make a module in terraform we will only need to specify the location of the folder. We do not need complex actions or definitions. In this example module2 will call module1 to generate the random string.

the file will only call the module1

module "kati" {
    source = "../module1"

In order to call the module I will need to perform an apply on module2.

cd module2; terraform apply

As we have not specified an output variable in module2 the result will not be printed in the console, you can see from below screenshot that module2 is calling kati file from module1 to generate the random string.

However we can find the result by navigating in the terraform.tfstate file of module2.

When we have more complex scenarios we will need to pass variables inside the calling modules. In order to learn how to pass variables in the calling modules you can read my previous article.

You can find the example on GitHub

Modules – Configuration Language | Terraform | HashiCorp Developer

Youtube video: