All guides

Terraform modules: when to write one and how to version it

A module is a set of Terraform configuration files in a single directory. HashiCorp's documentation says when one is worth writing, where provider configuration belongs and how a caller pins a version.

Close-up of code on a screen in many colours

When a module earns its place

In principle, any combination of resources can be factored out into a module. HashiCorp's documentation adds that overusing modules makes a configuration harder to understand and maintain, and it recommends moderation. Its test for a good module: the module raises the level of abstraction. It describes a new concept in your architecture and builds that concept out of the resource types providers offer.

The documentation's example is a module for a HashiCorp Consul cluster running in AWS, built from aws_instance, aws_elb and other AWS resources. It does not recommend modules that are thin wrappers around a single resource type. Its check is the name. If you have trouble finding a name for the module that differs from the main resource type inside it, the documentation reads that as a sign of a module that creates no new abstraction. Use the resource type directly in the calling module.

Inputs and outputs

HashiCorp's page on values in modules says variables define the input interface of a module, the values it accepts as arguments. An output's value is what Terraform returns for it, and a caller reads it as module.<NAME>.<OUTPUT>.

HCL

variable "environment" {
  type        = string
  description = "Environment name, used in resource names and tags."

  validation {
    condition     = contains(["dev", "staging", "prod"], var.environment)
    error_message = "The environment must be dev, staging or prod."
  }
}

output "bucket_name" {
  description = "Name of the bucket the module creates."
  value       = aws_s3_bucket.bucket.bucket
}

The three environment names are the example's choice. List your own.

  • Give every variable and output a description. The standard module structure asks for one or two sentences that explain its purpose.
  • Set a type on each variable. It specifies a type constraint for the value.
  • Set a default only where the argument should be optional. A variable with no default requires a value.
  • Use validation for a rule beyond the type. Terraform proceeds with an operation only when the condition evaluates to true, and it displays the error_message when the condition is false.

Providers stay in the root module

Each module must declare its own provider requirements, and provider configurations can be defined only in a root module. HashiCorp's rule for shared modules reads: A module that other modules call must contain no provider block. The default provider configurations of the parent pass to a child module automatically.

HCL

terraform {
  required_version = ">= 1.9.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = ">= 5.0"
    }
  }
}

The version numbers are the example's choice. Set the minimums your module needs. The documentation adds three rules:

  • For a shared module, constrain only the minimum required provider version, with >=.
  • A root module should use a ~> constraint, which sets both a lower and an upper bound for each provider.
  • for_each, count and depends_on do not work with a module that carries its own provider configurations.

A module that needs an aliased provider configuration declares the alias names with configuration_aliases. Aliased configurations must always be passed explicitly. The caller sets them in the providers argument of the module block.

Versions for callers

HCL

module "network" {
  source  = "my-org/network/aws"
  version = "~> 2.1"
}

module "network_from_git" {
  source = "git::https://github.com/my-org/terraform-aws-network.git?ref=v2.1.0"
}

The module name, the repository and the version numbers are the example's choice.

The version argument applies only when a module is installed from a registry. When it is left out, it defaults to the latest version available, and HashiCorp recommends constraining it to avoid unexpected or unwanted changes. The ~> operator allows only the right-most version component to increment. HashiCorp's example: ~> 1.1 allows 1.2 and 1.10 but not 2.0.

For a Git source, the ref query parameter selects the revision. It takes any value that git checkout supports, such as a branch, a SHA-1 hash or a tag.

The public Terraform Registry requires release tags that are semantic versions, with an optional v prefix. HashiCorp's guidance on constraints has two parts. Require specific versions of third-party modules, so that updates happen only when convenient to you. Use version ranges for modules your organization maintains with consistent semantic versioning.

Small modules that compose

The documentation's strong recommendation is a flat module tree with a single level of child modules. It favors small modules whose dependencies arrive as inputs. In its example, a network module outputs vpc_id and subnet_ids, and the root module passes both to a Consul cluster module as arguments. The cluster module does not know or care how the calling module obtained those identifiers.

Examples and documentation

The standard module structure recommends main.tf, variables.tf and outputs.tf in the root directory, with a README and a license file. Nested modules go under modules/, and examples of using the module go under examples/.

To publish on the public Terraform Registry, the module must be in a public GitHub repository named terraform-<PROVIDER>-<NAME>, follow the standard module structure and tag its releases with semantic versions.

Checks before a release

  • The module contains no provider block, and required_providers sets a minimum version.
  • Every variable has a type, and every variable and output has a description.
  • An example of using the module sits under examples/.
  • A renamed resource has a moved block. By default Terraform reads a changed address as an instruction to destroy the existing resource and create a new one.
  • The release tag is a semantic version.
  • Each caller sets version, or a ref for a Git source.

Sources

Want a second pair of eyes on yours? We do this work for a living.

Book a call

More guides