Movatterモバイル変換


[0]ホーム

URL:


HashiConf 2025Don't miss the live stream of HashiConf Day 2 happening now View live stream

You are viewing documentation for version v1.7.x.View latest version.

Hands-on: Try theReuse Configuration with Modules tutorials.

Amodule is a container for multiple resources that are used together.

Every Terraform configuration has at least one module, known as itsroot module, which consists of the resources defined in the.tf files inthe main working directory.

A module can call other modules, which lets you include the child module'sresources into the configuration in a concise way. Modulescan also be called multiple times, either within the same configuration orin separate configurations, allowing resource configurations to be packagedand re-used.

This page describes how to call one module from another. For more informationabout creating re-usable child modules, seeModule Development.

Calling a Child Module

Tocall a module means to include the contents of that module into theconfiguration with specific values for itsinput variables. Modules are calledfrom within other modules usingmodule blocks:

module "servers" {  source= "./app-cluster"  servers= 5}

A module that includes amodule block like this is thecalling module of thechild module.

The label immediately after themodule keyword is a local name, which thecalling module can use to refer to this instance of the module.

Within the block body (between{ and}) are the arguments for the module.Module calls use the following kinds of arguments:

  • Thesource argument is mandatory for all modules.

  • Theversion argument is recommended for modules from a registry.

  • Most other arguments correspond toinput variablesdefined by the module. (Theservers argument in the example above is one ofthese.)

  • Terraform defines a few other meta-arguments that can be used with allmodules, includingfor_each anddepends_on.

Source

All modulesrequire asource argument, which is a meta-argument defined byTerraform. Its value is either the path to a local directory containing themodule's configuration files, or a remote module source that Terraform shoulddownload and use. This value must be a literal string with no templatesequences; arbitrary expressions are not allowed. For more information onpossible values for this argument, seeModule Sources.

The same source address can be specified in multiplemodule blocks to createmultiple copies of the resources defined within, possibly with differentvariable values.

After adding, removing, or modifyingmodule blocks, you must re-runterraform init to allow Terraform the opportunity to adjust the installedmodules. By default this command will not upgrade an already-installed module;use the-upgrade option to instead upgrade to the newest available version.

Version

When using modules installed from a module registry, we recommend explicitlyconstraining the acceptable version numbers to avoid unexpected or unwantedchanges.

Use theversion argument in themodule block to specify versions:

module "consul" {  source  = "hashicorp/consul/aws"  version = "0.0.5"  servers = 3}

Theversion argument accepts aversion constraint string.Terraform will use the newest installed version of the module that meets theconstraint; if no acceptable versions are installed, it will download the newestversion that meets the constraint.

Version constraints are supported only for modules installed from a moduleregistry, such as the publicTerraform RegistryorHCP Terraform's private module registry.Other module sources can provide their own versioning mechanisms within thesource string itself, or might not support versions at all. In particular,modules sourced from local file paths do not supportversion; sincethey're loaded from the same source repository, they always share the sameversion as their caller.

Meta-arguments

Along withsource andversion, Terraform defines a few moreoptional meta-arguments that have special meaning across all modules,described in more detail in the following pages:

  • count - Creates multiple instances of a module from a singlemodule block.Seethecount pagefor details.

  • for_each - Creates multiple instances of a module from a singlemoduleblock. Seethefor_each pagefor details.

  • providers - Passes provider configurations to a child module. Seetheproviders pagefor details. If not specified, the child module inherits all of the default(un-aliased) provider configurations from the calling module.

  • depends_on - Creates explicit dependencies between the entiremodule and the listed targets. Seethedepends_on pagefor details.

Terraform does not use thelifecycle argument. However, thelifecycle block is reserved for future versions.

Accessing Module Output Values

The resources defined in a module are encapsulated, so the calling modulecannot access their attributes directly. However, the child module candeclareoutput values to selectivelyexport certain values to be accessed by the calling module.

For example, if the./app-cluster module referenced in the example aboveexported an output value namedinstance_ids then the calling modulecan reference that result using the expressionmodule.servers.instance_ids:

resource "aws_elb" "example" {  # ...  instances= module.servers.instance_ids}

For more information about referring to named values, seeExpressions.

Transferring Resource State Into Modules

Movingresource blocks from one module into several child modules causesTerraform to see the new location as an entirely different resource. As aresult, Terraform plans to destroy all resource instances at the old addressand create new instances at the new address.

To preserve existing objects, you can userefactoring blocks to record the old and newaddresses for each resource instance. This directs Terraform to treat existingobjects at the old addresses as if they had originally been created at thecorresponding new addresses.

Replacing resources within a module

You may have an object that needs to be replaced with a new object for a reasonthat isn't automatically visible to Terraform, such as if a particular virtualmachine is running on degraded underlying hardware. In this case, you can usethe-replace=... planning optionto force Terraform to propose replacing that object.

If the object belongs to a resource within a nested module, specify the fullpath to that resource including all of the nested module steps leading to it.For example:

$ terraform plan -replace=module.example.aws_instance.example

The above selects aresource "aws_instance" "example" declared inside amodule "example" child module declared inside your root module.

Because replacing is a very disruptive action, Terraform only allows selectingindividual resource instances. There is no syntax to force replacingallresource instances belonging to a particular module.

Removing Modules

Note: Theremoved block is available in Terraform v1.7 and later. For earlier Terraform versions, you can use theterraform state rm CLI command as a separate step.

To remove a module from Terraform, simply delete the module call from your Terraform configuration.

By default, after you remove themodule block, Terraform will plan to destroy any resources it is managing that were declared in that module. This is because when you remove the module call, that module's configuration is no longer included in your Terraform configuration.

Sometimes you may wish to remove a module from your Terraform configuration without destroying the real infrastructure objects it manages. In this case, the resources will be removed from theTerraform state, but the real infrastructure objects will not be destroyed.

To declare that a module was removed from Terraform configuration but that its managed objects should not be destroyed, remove themodule block from your configuration and replace it with aremoved block:

removed {  from= module.example  lifecycle {    destroy= false  }}

Thefrom argument is the address of the module you want to remove, without any instance keys (such as "module.example[1]").

Thelifecycle block is required. Thedestroy argument determines whether Terraform will attempt to destroy the objects managed by the module or not. A value offalse means that Terraform will remove the resources from state without destroying them.

Edit this page on GitHub

[8]ページ先頭

©2009-2025 Movatter.jp