Go to content
Infrastructure

Getting Started with Terraform Modules

When you use Terraform to manage cloud infrastructure, you may start with a few resources and later need the same related resources in several environments. A Terraform module groups resources and their settings so you can manage and reuse them together. The configuration in your working directory is the root module. Any module it calls is a child module.

Start with a local child module when you have a clear group of infrastructure to reuse, such as a network used by several environments. Give the module a small, documented interface: inputs callers set and outputs they can use. Then run terraform init to install it, review the planned changes, and run terraform apply only after you understand what Terraform will create or change. These basics also support more advanced work, such as publishing modules, pinning versions, passing provider configurations, and moving existing resources safely.

Create a local module and call it

A module is a directory that contains Terraform configuration files. Terraform treats all the files in one directory as a single module. You can put its configuration in main.tf, variables.tf, and outputs.tf without changing how a caller uses it. HashiCorp’s modules overview explains how root and child modules relate and how modules help you reuse related resources.

A practical starting layout separates the root configuration from the child module:

.
├── main.tf
├── variables.tf
└── modules/
    └── network/
        ├── main.tf
        ├── variables.tf
        └── outputs.tf

Use the modules/network directory for a useful concept, such as the network resources an environment needs. Avoid creating a module for every individual resource: a thin wrapper adds another layer for readers to follow without giving callers a useful way to manage related resources. Consider a module when it groups resources that you expect to configure the same way in more than one place. For more on that choice, see when to use Terraform modules.

In the child module, declare required caller-supplied values as variables. A variable’s type sets the kind of value it accepts, and its description tells callers what that value means.

# modules/network/variables.tf
variable "name" {
  type        = string
  description = "Name used to identify this network."
}

The root module calls the child in a module block. The source argument tells Terraform where to find it. Here, the path points to a directory in the same repository.

# main.tf
module "network" {
  source = "./modules/network"

  name = var.network_name
}

The root module also needs to declare network_name as an input variable. A child module can make values available through outputs. The caller refers to an output as module.<NAME>.<OUTPUT>. For example, if the child declares an output named network_id, the root module can refer to it as module.network.network_id. The child should expose the values callers need, not every detail of how it creates its resources.

To use the module, run terraform init from the root directory. Terraform downloads or copies the module files into its working directory. Then run terraform plan to review proposed changes before running terraform apply to make them. HashiCorp’s module configuration documentation covers module sources, inputs, outputs, and initialization.

Design an interface callers can understand

Treat variables and outputs as the module’s public interface, the values callers can provide and receive. Give every input a type and description. Set a default only when the input is optional; otherwise, require the caller to provide it. If the type cannot express a rule that a valid value must meet, add a variable validation condition and an error message that explains the problem. Terraform stops when the condition evaluates to false.

Keep the interface focused on choices the caller should control. A network module, for example, can accept a name and configuration values the caller already knows, then return identifiers other resources need. A service module that needs a network identifier should accept it as an input. It does not need to know how another module created the network. This makes modules easier to reuse and keeps the module tree relatively flat, with the root module coordinating its child modules.

Terraform infers dependencies from references between resources and module arguments. When a module argument uses a resource’s value, Terraform orders the related operations based on that reference. Use depends_on in a module block when the configuration does not show a dependency through an argument reference. The module configuration reference explains how Terraform handles module dependencies.

A root module can call the same child module more than once. Use count to create a specified number of similarly configured instances. Use for_each to create instances from a set of keys. Choose the option that fits your data and how you want to identify each instance. See how for_each and count work in modules.

Choose a source and control updates

A local path works well when you develop a module alongside the configuration that calls it. To reuse modules across repositories, Terraform also supports registry modules, Git repositories, and object storage sources. Choose a source based on who needs access and how you plan to release changes. The local and remote module comparison can help you make that choice.

Registry module blocks can specify a version constraint. Constrain versions to prevent an upstream release from changing your infrastructure configuration unexpectedly. The exact range matters. For example, the ~> 1.1 constraint allows versions such as 1.2 and 1.10, but not 2.0. Check your constraint; different ~> expressions allow different updates.

Git sources use a different setting. A Git source can include a ref query parameter to select a branch, tag, or commit hash. Without ref, Terraform uses the repository’s default branch. The module version argument applies to registry modules, not Git sources. Tags for a released public Registry module must use semantic versioning, with an optional v prefix.

After changing a module’s source or registry version, run terraform init again. Run terraform init -upgrade when you want Terraform to update installed modules within the version constraints. For third-party modules, a specific version lets you choose when to adopt an update. For modules that follow semantic versioning consistently, a version range can allow compatible releases while excluding a major-version change.

Pass provider configurations from the root

A provider configuration tells Terraform how to connect to a provider, such as a cloud service. Put provider configuration blocks in the root module, not in a shared child module. A child module inherits the root’s default provider configuration. Terraform does not automatically pass aliased configurations, such as a second configuration for another region.

Pass an aliased configuration explicitly in the module block’s providers map. If the child needs more than one configuration for a provider, declare the expected aliases with configuration_aliases in its provider requirements. Each module should declare its own provider requirements. Shared modules should state the minimum provider version they need, rather than forcing every caller to use a narrow range of versions. HashiCorp’s provider configuration guidance for modules explains inheritance and explicit mapping.

This setup also matters when you use count, for_each, or depends_on in a module block. Terraform’s legacy pattern of defining provider configurations inside child modules does not work with those module-level arguments. Remove provider blocks from shared child modules so callers can manage provider configurations in the root and pass the needed configuration explicitly.

Move or remove modules without surprises

When you move a resource into a child module, its address changes, and Terraform can interpret it as a different object. A moved block tells Terraform how the old address maps to the new one. The address change then does not itself request destruction and recreation. For example, when you move a root-level resource into a child module, declare the old and new addresses in a moved block. Review the plan before applying.

Removing a module block and applying normally destroys the resources it manages, and Terraform removes them from its state. If you need Terraform to stop managing a module’s resources while leaving the real infrastructure in place, use a removed block with destroy = false. Both changes affect Terraform state and infrastructure. Inspect the plan and confirm it matches your intent before applying.

More in Infrastructure Back to top ↑