Lesson 5 of 7 in Infrastructure as Code with Terraform and OpenTofu

Modules: reusing configuration safely

Core11 min

A module is a folder of Terraform/OpenTofu files that you call from another configuration, like a function with inputs and outputs. Every configuration is already a module, called the root module, and it can call child modules.

Draft. This lesson is written and waiting for a person to run every command and review it. It is safe to learn from, but check the official documentation for anything you depend on.

Read these first: Resources, variables and outputs

The problem this solves

Once you have several environments or teams, you build the same group of resources again and again. Copy-pasting those blocks means a fix must be repeated in every copy.

A module lets you write the group once and call it with different inputs. Teams also publish modules, so you do not hand-write common patterns from scratch.

How it works

One module, called twice with different inputs
One module, called twice with different inputsThe root configuration calls the same module twice. Each call has its own inputs and creates its own resources.1 inputs1 inputs2 creates2 createsRoot configyour main.tfmodule aname = alphamodule bname = betaalpha.txtcreated by abeta.txtcreated by b
  • Control
  • Runs code
  • Data

The root configuration calls the same module twice. Each call has its own inputs and creates its own resources.

  1. Root config to module a: 1 inputs
  2. Root config to module b: 1 inputs
  3. module a to alpha.txt: 2 creates
  4. module b to beta.txt: 2 creates

A module has three parts. Its variables are the inputs, its resources do the work, and its outputs are the only values the caller can read. The caller cannot reach inside a module's resources directly.

In the caller, a module block names the instance and gives a source. The source can be a local folder, a Git address, or a registry address. Each distinct block is a separate instance with its own resources in state, shown under addresses like module.a.local_file.this.

Registry and Git modules take a version or a pinned ref. Pin it. An unpinned module can change under you on the next init -upgrade, and a module change affects every caller.

Try it yourself

A local module with the free local provider. No registry access is needed for the module itself.

  1. 1
    Write the module
    mkdir -p ~/iac-lab/modules/modules/note && cd ~/iac-lab/modules
    cat > modules/note/main.tf <<"EOF"
    terraform {
      required_providers {
        local = { source = "hashicorp/local" }
      }
    }
    
    variable "name" {
      type = string
    }
    
    resource "local_file" "this" {
      filename = format("%s.txt", var.name)
      content  = format("This note belongs to %s", var.name)
    }
    
    output "path" {
      value = local_file.this.filename
    }
    EOF
  2. 2
    Call it twice from the root
    cat > main.tf <<"EOF"
    module "a" {
      source = "./modules/note"
      name   = "alpha"
    }
    
    module "b" {
      source = "./modules/note"
      name   = "beta"
    }
    
    output "paths" {
      value = [module.a.path, module.b.path]
    }
    EOF
    terraform plan

    Expect an error that the module is not installed and that you must run terraform init. Adding or changing a module source always needs init.

  3. 3
    Init and apply
    terraform init
    terraform apply -auto-approve
    ls *.txt

    You should see alpha.txt and beta.txt.

  4. 4
    Inspect and clean up
    terraform state list
    terraform destroy -auto-approve

    The state addresses start with module.a. and module.b., which shows each call is a separate instance.

What breaks, and where to look

  • Error: Module not installed. This module is not yet installed. Run "terraform init" to install all modules required by this configuration.

    WHY IT HAPPENS
    You added a module block or changed its source and have not run init since.
    CHECK FIRST
    Run terraform init in the root folder.
  • Error: Unsupported attribute, This object does not have an attribute named "something".

    WHY IT HAPPENS
    You referenced a value from a module that the module does not export as an output. Callers see outputs only.
    CHECK FIRST
    Open the module's files and look for the output block. Add one if the value is needed.
  • A plan shows surprising changes after you ran init on a new machine or in CI, with no edits from you.

    WHY IT HAPPENS
    A registry or Git module had no version pin, so a newer version was downloaded.
    CHECK FIRST
    Look at the module block for a version argument or a pinned Git ref. Compare .terraform/modules/modules.json between machines.

When not to use this

  • Do not wrap a single resource in a module just to look organised. A module is worth it once the same group is used in a few places.
  • Deeply nested modules hide what is being built. Keep one or two levels and prefer small modules with clear inputs.

Check yourself

How does a caller read a value from inside a module?

Only through the module's outputs, written as module.<name>.<output>.

Why must you run init after adding a module block?

init downloads or links the module's code. Without it the tool reports the module as not installed.

Why pin a module version?

So the same code is used every time and nobody gets different changes just by running init later.

Lesson 67 of 92 in the DevOps path

Search

Search cheat sheets and projects