Advanced Module Usage and Registry Practices · Topic 1 of 2

Refactoring into Modules and the Module Contract

Terraform Professional (002): when a module is justified, moving resources with moved blocks, and the inputs, outputs and provider rules of a module.

  • 5 min
In a nutshell
  • A good module adds an abstraction; a thin wrapper does not.
  • Scope modules by encapsulation, privileges and volatility.
  • moved changes the tracked address, so nothing is replaced if the configuration matches.

What it is

A module should add a new abstraction: a higher-level concept built from several resources, such as an application tier. Refactoring turns repeated or tangled configuration into that abstraction without replacing what is already running.

A module's contract is what callers can rely on: its input variables, its outputs, and its provider and version requirements. Everything else is private, so you can change it freely.

How it works

When to create a module

SignalDecision
The same group of resources repeats across configurationsCreate a module
Resources are always deployed togetherGroup them
Resources need different privilegesKeep them in separate modules
Long-lived data sits beside often-changing app serversSeparate them by volatility
It wraps a single resource typeDo not create a module

HashiCorp's test for a thin wrapper: if you struggle to name the module differently from the main resource inside it, it adds no abstraction. Overusing modules makes configuration harder to understand.

Keep the tree flat, with about one level of child modules, and connect modules in the root through expressions. Pass dependencies in as inputs, such as a subnet ID, rather than having a module create or detect them. This is called dependency inversion.

Moving resources without replacing them

Moving a resource block into a module changes its address. Without help, Terraform sees one object removed and a new one added.

module "web" {
  source = "./modules/web"
  name   = var.name
}

moved {
  from = aws_instance.web
  to   = module.web.aws_instance.web
}

Trace the plan for an instance already in state at aws_instance.web:

  1. Terraform reads the moved block and updates the tracked address to module.web.aws_instance.web.
  2. It compares the object against the module's configuration.
  3. If the arguments match, the plan shows the move and 0 to add, 0 to destroy.

Without the moved block, the same plan shows 1 to add and 1 to destroy. Run terraform init first, because a new module call has to be installed.

Resource in rootmoved blockSame objectnew address in moduleterraform planNo replacement

A module may only make moved statements about its own objects and those of its child modules. Keep old moved blocks in shared modules, because removing one makes callers who have not upgraded plan a delete.

The contract: inputs

DeclarationEffect on the caller
Variable with no defaultRequired
Variable with a defaultOptional
type constraintWrong types fail with a clear error
validation blockFails with your error message
optional() attribute in an objectCaller may omit it

optional() behaves in a way worth tracing.

variable "site" {
  type = object({
    bucket = string
    index  = optional(string, "index.html")
    prefix = optional(string)
  })
}

Given site = { bucket = "docs", index = null }, the result is bucket = "docs", index = "index.html" and prefix = null. An explicit null on an optional attribute with a non-null default takes that default, and an attribute with no default becomes null.

The contract: outputs

Outputs are the only way to read values from a module, as in module.web.instance_id. A reference such as module.web.aws_instance.web.id fails, because a child's resources are not visible to the caller.

An output is part of the contract, so document it with a description. An output that exposes a sensitive value must itself set sensitive = true.

The contract: providers

RuleDetail
No provider blocks in a shared moduleThe root configures providers
Declare required_providers in each moduleRequirements are not inherited
Use >= for shared module provider versionsSet only a minimum
Default provider configurationsInherited automatically
Aliased configurationsPass with the providers argument and declare configuration_aliases

A module with its own provider blocks cannot be called with for_each, count or depends_on; Terraform raises an error. A module can also set required_version, and the CLI must satisfy every constraint in the tree.

What breaks callers

Renaming or removing a variable or output breaks callers, as does adding a required variable. Adding an optional variable, an optional() attribute or a new output does not.

How the exam asks about this

  • "A module contains one aws_s3_bucket and passes every argument through." It is a thin wrapper; use the resource directly.
  • "Moving resources into a module plans to destroy and recreate them." Add moved blocks for each address.
  • "A parent needs an ID from a resource in a child module." Add an output to the child and reference module.NAME.OUTPUT.

What to remember for the exam

  • A good module adds an abstraction; a thin wrapper does not.
  • Scope modules by encapsulation, privileges and volatility.
  • moved changes the tracked address, so nothing is replaced if the configuration matches.
  • Callers reach module values only through outputs.
  • Shared modules declare required_providers but contain no provider blocks.
  • Aliased provider configurations are never inherited; pass them explicitly.
Watch out

Removing a moved block from a shared module is a breaking change. A caller still at the old address will plan to delete the object instead of moving it.

Common mistakes

Putting a provider block in a reusable module. The caller loses the ability to use for_each or count on it. Configure providers in the root.

Having a module detect whether something exists. Conditional creation inside a module hides intent. Accept the object as an input, and let the caller create it or look it up with a data source.

Renaming a variable in a minor release. A variable name is part of the contract. Treat the rename as a breaking change and document the migration.

Check yourself

  • What does the plan show when a moved block matches a resource moved into a module?

    It shows the address change with nothing to add or destroy, as long as the arguments in the module match the object.

  • Why can a caller not reference module.web.aws_instance.web.id?

    A child module's resources are private, so the module must expose the value through an output.

  • How does a child module get an aliased provider configuration?

    The caller passes it with the providers argument, and the child declares the alias with configuration_aliases in required_providers.

Topic 1 of 2 in Advanced Module Usage and Registry Practices

Test yourself on Advanced Module Usage and Registry Practices

The full HashiCorp Terraform Infrastructure Engineer Professional question bank has 600 questions, with timed practice exams and an explanation for every answer.

This study guide is independent and is not affiliated with, endorsed by, or sponsored by HashiCorp. Vendor names, certification names and exam codes are trademarks of their respective owners and are used for identification only.