Andrew Mercer
on this page

A module is a directory of .tf files. Every Terraform configuration is a module; the one you run plan in is the root module, and anything it calls with a module block is a child module.

This page covers module mechanics and interface design. For how modules fit into an estate (resource vs composition modules, layering, repos), read the architecture guide. For versioning and distributing modules across many repositories, see shared modules.

Calling a module

module "network" {
  source  = "app.terraform.io/acme/network/azurerm"   # where the code is
  version = "~> 3.2"                                   # registry sources only

  # Inputs: the child's variables
  name          = "vnet-app-${var.env}-cc"
  address_space = ["10.10.0.0/16"]
  subnets = {
    aks  = { address_prefix = "10.10.0.0/22" }
    data = { address_prefix = "10.10.4.0/24" }
  }
  tags = local.tags
}

# Outputs: module.<name>.<output>
resource "azurerm_kubernetes_cluster" "this" {
  # ...
  default_node_pool {
    vnet_subnet_id = module.network.subnet_ids["aks"]
    # ...
  }
}

After adding or changing a module block's source or version, run terraform init (or init -upgrade to move to a newer allowed version).

Module sources

Source Syntax Version pinning
Local path "../modules/network" None. Always the current files
Public registry "Azure/avm-res-network-virtualnetwork/azurerm" version = "~> 0.8"
Private registry (HCP, GitLab, etc.) "gitlab.example.com/group/network/azurerm" version = "..."
Git (HTTPS) "git::https://gitlab.com/acme/tf-modules.git//network?ref=v3.2.1" ?ref= tag or commit
Git (SSH) "git::ssh://[email protected]/acme/tf-modules.git//network?ref=v3.2.1" ?ref=
GitHub/Bitbucket shorthand "github.com/acme/tf-modules//network?ref=v3.2.1" ?ref=
HTTP archive, S3, GCS "s3::https://...", "gcs::https://..." Path/object versioning
OCI registry (OpenTofu 1.10+) "oci://registry.example.com/modules/network?tag=3.2.1" Tag or digest

Notes:

  • // separates the repository (what gets downloaded) from the subdirectory (what gets loaded), so modules can reference siblings with relative paths.
  • Pin Git refs to tags or commit SHAs, never branches. ?ref=main means prod picks up whatever merged last.
  • Terraform 1.15+ (and OpenTofu 1.8+) allow variables and locals in source and version, as long as they're known before init. That makes version = var.network_module_version possible, which helps when a pipeline injects versions. Static literals remain easier to grep, diff and bump with Renovate.

Module structure

modules/network/
├── README.md            # generated by terraform-docs, plus examples
├── main.tf              # resources
├── variables.tf         # inputs
├── outputs.tf           # outputs
├── versions.tf          # required_version + required_providers (no provider config)
├── locals.tf            # optional
├── examples/
│   └── basic/main.tf    # runnable example, also used by tests
└── tests/
    └── basic.tftest.hcl # terraform test

File naming conventions are in hygiene.

Designing the interface

A module's interface is its variables and outputs. Most of the guidance on variables, outputs and locals applies; these are the module-specific rules.

Inputs

  • Require only what has no sensible default. Name, location, resource group. Everything else gets a secure default.
  • Secure by default. Public network access off, TLS 1.2 minimum, diagnostics on, encryption on. Callers opt out explicitly, which makes risky choices visible in review.
  • Use typed objects with optional() for groups of related settings, not twenty flat variables:

hcl variable "network" { type = object({ public_access_enabled = optional(bool, false) allowed_ip_ranges = optional(list(string), []) subnet_id = optional(string) }) default = {} }

  • Accept maps for collections (map(object)) so you can for_each with stable keys.
  • Validate early with validation blocks: naming rules, CIDR shapes, allowed SKUs.
  • No environment names in modules. Never if var.env == "prod". Expose the capability (zone_redundant, sku, replica_count) and let the root decide.
  • Don't pass-through every provider argument. A module that mirrors one resource argument-for-argument adds a layer and no value. A good module encodes your organisation's decisions: naming, tagging, diagnostics, private endpoints, RBAC.

Outputs

  • Return IDs and names callers need for wiring, keyed by meaningful map keys.
  • Mark secrets sensitive. Better, don't output secrets: output the Key Vault secret ID instead.
  • Use deprecated (Terraform 1.15+) on outputs you plan to remove.

Providers in modules

Child modules declare providers; they never configure them.

# modules/network/versions.tf
terraform {
  required_version = ">= 1.9"
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = ">= 4.0, < 5.0"     # a range, not an exact pin
    }
  }
}

Why:

  • A provider block inside a child module makes the module unusable with count, for_each and depends_on.
  • Removing a module that configures its own provider strands its resources: Terraform needs the provider config to destroy them, and it went away with the module.
  • The root module knows credentials, subscriptions and regions. Modules shouldn't.

Version constraints in modules should be ranges (>= 4.0, < 5.0); exact pins belong in the root module's lock file. If every module pins = 4.12.0, the root can never upgrade.

For modules that need more than one configuration of a provider (hub/spoke, cross-region replication), use configuration_aliases. See meta-arguments.

Composition

Prefer shallow trees: a root module calls a handful of modules, and those modules mostly contain resources. Deep nesting (module calls module calls module) makes plans hard to read, outputs tedious to thread through, and refactoring expensive.

# Root module: composes, doesn't contain much logic itself
module "network" { source = "../../modules/network"  /* ... */ }
module "keyvault" {
  source    = "../../modules/keyvault"
  subnet_id = module.network.subnet_ids["private-endpoints"]
}
module "aks" {
  source       = "../../modules/aks"
  subnet_id    = module.network.subnet_ids["aks"]
  key_vault_id = module.keyvault.id
}

Dependency inversion: pass dependencies in as variables (subnet_id) rather than having the module look them up or create them. The module becomes usable in more contexts, and testable with mock IDs.

Data-only modules

A module with no resources, only data sources and outputs, is a clean way to share lookups:

# modules/platform-lookup: "where is the shared stuff for this environment?"
data "azurerm_virtual_network" "hub" {
  name                = "vnet-hub-${var.env}-cc"
  resource_group_name = "rg-connectivity-${var.env}"
}
output "hub_vnet_id" { value = data.azurerm_virtual_network.hub.id }

Consumers get one place where naming conventions are encoded, instead of every stack repeating the lookup.

Public modules: Azure Verified Modules and friends

Before writing a module, check:

  • Azure Verified Modules (AVM): Microsoft's official, tested resource and pattern modules (Azure/avm-res-*, Azure/avm-ptn-*).
  • terraform-aws-modules: the de facto AWS standard set.
  • terraform-google-modules and Google's Cloud Foundation Fabric.

Wrap a public module in a thin internal module when you need to enforce your defaults, so you can swap or upgrade the public one in one place.

Documentation

Generate the README with terraform-docs and enforce it in pre-commit or CI:

# .terraform-docs.yml
formatter: markdown table
output:
  file: README.md
  mode: inject          # writes between <!-- BEGIN_TF_DOCS --> markers
sort:
  by: required

Every module should have at least one runnable example under examples/; it doubles as test fixture and documentation.

in this section
* shared modules: registries, versioning and upgrades at scale