github.com/rstandt/terraform@v0.12.32-0.20230710220336-b1063613405c/website/docs/configuration/modules.html.md (about)

     1  ---
     2  layout: "docs"
     3  page_title: "Modules - Configuration Language"
     4  sidebar_current: "docs-config-modules"
     5  description: |-
     6    Modules allow multiple resources to be grouped together and encapsulated.
     7  ---
     8  
     9  # Modules
    10  
    11  -> **Note:** This page is about Terraform 0.12 and later. For Terraform 0.11 and
    12  earlier, see
    13  [0.11 Configuration Language: Modules](../configuration-0-11/modules.html).
    14  
    15  A _module_ is a container for multiple resources that are used together.
    16  
    17  Every Terraform configuration has at least one module, known as its
    18  _root module_, which consists of the resources defined in the `.tf` files in
    19  the main working directory.
    20  
    21  A module can call other modules, which lets you include the child module's
    22  resources into the configuration in a concise way. Modules
    23  can also be called multiple times, either within the same configuration or
    24  in separate configurations, allowing resource configurations to be packaged
    25  and re-used.
    26  
    27  This page describes how to call one module from another. Other pages in this
    28  section of the documentation describe the different elements that make up
    29  modules, and there is further information about how modules can be used,
    30  created, and published in [the dedicated _Modules_
    31  section](/docs/modules/index.html). You can also learn more about how to use and
    32  create modules with our hands-on [modules track on
    33  learn.hashicorp.com](https://learn.hashicorp.com/terraform/modules/modules-overview?utm_source=WEBSITE&utm_medium=WEB_IO&utm_offer=ARTICLE_PAGE&utm_content=DOCS).
    34  
    35  ## Calling a Child Module
    36  
    37  To _call_ a module means to include the contents of that module into the
    38  configuration with specific values for its
    39  [input variables](./variables.html). Modules are called
    40  from within other modules using `module` blocks:
    41  
    42  ```hcl
    43  module "servers" {
    44    source = "./app-cluster"
    45  
    46    servers = 5
    47  }
    48  ```
    49  
    50  A module that includes a `module` block like this is the _calling module_ of the
    51  child module.
    52  
    53  The label immediately after the `module` keyword is a local name, which the
    54  calling module can use to refer to this instance of the module.
    55  
    56  Within the block body (between `{` and `}`) are the arguments for the module.
    57  Most of the arguments correspond to [input variables](./variables.html)
    58  defined by the module, including the `servers` argument in the above example.
    59  Terraform also defines a few meta-arguments that are reserved by Terraform
    60  and used for its own purposes; we will discuss those throughout the rest of
    61  this section.
    62  
    63  All modules require a `source` argument, which is a meta-argument defined by
    64  Terraform CLI. Its value is either the path to a local directory of the
    65  module's configuration files, or a remote module source that Terraform should
    66  download and use. This value must be a literal string with no template
    67  sequences; arbitrary expressions are not allowed. For more information on
    68  possible values for this argument, see [Module Sources](/docs/modules/sources.html).
    69  
    70  The same source address can be specified in multiple `module` blocks to create
    71  multiple copies of the resources defined within, possibly with different
    72  variable values.
    73  
    74  After adding, removing, or modifying `module` blocks, you must re-run
    75  `terraform init` to allow Terraform the opportunity to adjust the installed
    76  modules. By default this command will not upgrade an already-installed module;
    77  use the `-upgrade` option to instead upgrade to the newest available version.
    78  
    79  ## Accessing Module Output Values
    80  
    81  The resources defined in a module are encapsulated, so the calling module
    82  cannot access their attributes directly. However, the child module can
    83  declare [output values](./outputs.html) to selectively
    84  export certain values to be accessed by the calling module.
    85  
    86  For example, if the `./app-cluster` module referenced in the example above
    87  exported an output value named `instance_ids` then the calling module
    88  can reference that result using the expression `module.servers.instance_ids`:
    89  
    90  ```hcl
    91  resource "aws_elb" "example" {
    92    # ...
    93  
    94    instances = module.servers.instance_ids
    95  }
    96  ```
    97  
    98  For more information about referring to named values, see
    99  [Expressions](./expressions.html).
   100  
   101  ## Module Versions
   102  
   103  We recommend explicitly constraining the acceptable version numbers for
   104  each external module to avoid unexpected or unwanted changes.
   105  
   106  Use the `version` attribute in the `module` block to specify versions:
   107  
   108  ```shell
   109  module "consul" {
   110    source  = "hashicorp/consul/aws"
   111    version = "0.0.5"
   112  
   113    servers = 3
   114  }
   115  ```
   116  
   117  The `version` attribute value may either be a single explicit version or
   118  a version constraint expression. Constraint expressions use the following
   119  syntax to specify a _range_ of versions that are acceptable:
   120  
   121  * `>= 1.2.0`: version 1.2.0 or newer
   122  * `<= 1.2.0`: version 1.2.0 or older
   123  * `~> 1.2.0`: any non-beta version `>= 1.2.0` and `< 1.3.0`, e.g. `1.2.X`
   124  * `~> 1.2`: any non-beta version `>= 1.2.0` and `< 2.0.0`, e.g. `1.X.Y`
   125  * `>= 1.0.0, <= 2.0.0`: any version between 1.0.0 and 2.0.0 inclusive
   126  
   127  When depending on third-party modules, references to specific versions are
   128  recommended since this ensures that updates only happen when convenient to you.
   129  
   130  For modules maintained within your organization, a version range strategy
   131  may be appropriate if a semantic versioning methodology is used consistently
   132  or if there is a well-defined release process that avoids unwanted updates.
   133  
   134  Version constraints are supported only for modules installed from a module
   135  registry, such as the [Terraform Registry](https://registry.terraform.io/) or
   136  [Terraform Cloud's private module registry](/docs/cloud/registry/index.html).
   137  Other module sources can provide their own versioning mechanisms within the
   138  source string itself, or might not support versions at all. In particular,
   139  modules sourced from local file paths do not support `version`; since
   140  they're loaded from the same source repository, they always share the same
   141  version as their caller.
   142  
   143  ## Other Meta-arguments
   144  
   145  Along with the `source` meta-argument described above, module blocks have
   146  some more meta-arguments that have special meaning across all modules,
   147  described in more detail in other sections:
   148  
   149  * `version` - (Optional) A [version constraint](#module-versions)
   150    string that specifies which versions of the referenced module are acceptable.
   151    The newest version matching the constraint will be used. `version` is supported
   152    only for modules retrieved from module registries.
   153  
   154  * `providers` - (Optional) A map whose keys are provider configuration names
   155    that are expected by child module and whose values are corresponding
   156    provider names in the calling module. This allows
   157    [provider configurations to be passed explicitly to child modules](#passing-providers-explicitly).
   158    If not specified, the child module inherits all of the default (un-aliased)
   159    provider configurations from the calling module.
   160  
   161  In addition to the above, the argument names `count`, `for_each` and
   162  `lifecycle` are not currently used by Terraform but are reserved for planned
   163  future features.
   164  
   165  Since modules are a complex feature in their own right, further detail
   166  about how modules can be used, created, and published is included in
   167  [the dedicated section on modules](/docs/modules/index.html).
   168  
   169  ## Providers within Modules
   170  
   171  In a configuration with multiple modules, there are some special considerations
   172  for how resources are associated with provider configurations.
   173  
   174  While in principle `provider` blocks can appear in any module, it is recommended
   175  that they be placed only in the _root_ module of a configuration, since this
   176  approach allows users to configure providers just once and re-use them across
   177  all descendent modules.
   178  
   179  Each resource in the configuration must be associated with one provider
   180  configuration, which may either be within the same module as the resource
   181  or be passed from the parent module. Providers can be passed down to descendent
   182  modules in two ways: either _implicitly_ through inheritance, or _explicitly_
   183  via the `providers` argument within a `module` block. These two options are
   184  discussed in more detail in the following sections.
   185  
   186  In all cases it is recommended to keep explicit provider configurations only in
   187  the root module and pass them (whether implicitly or explicitly) down to
   188  descendent modules. This avoids the provider configurations from being "lost"
   189  when descendent modules are removed from the configuration. It also allows
   190  the user of a configuration to determine which providers require credentials
   191  by inspecting only the root module.
   192  
   193  Provider configurations are used for all operations on associated resources,
   194  including destroying remote objects and refreshing state. Terraform retains, as
   195  part of its state, a reference to the provider configuration that was most
   196  recently used to apply changes to each resource. When a `resource` block is
   197  removed from the configuration, this record in the state is used to locate the
   198  appropriate configuration because the resource's `provider` argument (if any)
   199  is no longer present in the configuration.
   200  
   201  As a consequence, it is required that all resources created for a particular
   202  provider configuration must be destroyed before that provider configuration is
   203  removed, unless the related resources are re-configured to use a different
   204  provider configuration first.
   205  
   206  ### Provider Version Constraints in Modules
   207  
   208  To declare that a module requires particular versions of a specific provider,
   209  use a [`required_providers`](terraform.html#specifying-required-provider-versions)
   210  block inside a `terraform` block:
   211  
   212  ```hcl
   213  terraform {
   214    required_providers {
   215      aws = ">= 2.7.0"
   216    }
   217  }
   218  ```
   219  
   220  Shared modules should constrain only the minimum allowed version, using a `>=`
   221  constraint. This specifies the minimum version the provider is compatible
   222  with while allowing users to upgrade to newer provider versions without
   223  altering the module source code.
   224  
   225  ### Implicit Provider Inheritance
   226  
   227  For convenience in simple configurations, a child module automatically inherits
   228  default (un-aliased) provider configurations from its parent. This means that
   229  explicit `provider` blocks appear only in the root module, and downstream
   230  modules can simply declare resources for that provider and have them
   231  automatically associated with the root provider configurations.
   232  
   233  For example, the root module might contain only a `provider` block and a
   234  `module` block to instantiate a child module:
   235  
   236  ```hcl
   237  provider "aws" {
   238    region = "us-west-1"
   239  }
   240  
   241  module "child" {
   242    source = "./child"
   243  }
   244  ```
   245  
   246  The child module can then use any resource from this provider with no further
   247  provider configuration required:
   248  
   249  ```hcl
   250  resource "aws_s3_bucket" "example" {
   251    bucket = "provider-inherit-example"
   252  }
   253  ```
   254  
   255  This approach is recommended in the common case where only a single
   256  configuration is needed for each provider across the entire configuration.
   257  
   258  In more complex situations there may be [multiple provider instances](/docs/configuration/providers.html#multiple-provider-instances),
   259  or a child module may need to use different provider settings than
   260  its parent. For such situations, it's necessary to pass providers explicitly
   261  as we will see in the next section.
   262  
   263  ### Passing Providers Explicitly
   264  
   265  When child modules each need a different configuration of a particular
   266  provider, or where the child module requires a different provider configuration
   267  than its parent, the `providers` argument within a `module` block can be
   268  used to define explicitly which provider configs are made available to the
   269  child module. For example:
   270  
   271  ```hcl
   272  # The default "aws" configuration is used for AWS resources in the root
   273  # module where no explicit provider instance is selected.
   274  provider "aws" {
   275    region = "us-west-1"
   276  }
   277  
   278  # A non-default, or "aliased" configuration is also defined for a different
   279  # region.
   280  provider "aws" {
   281    alias  = "usw2"
   282    region = "us-west-2"
   283  }
   284  
   285  # An example child module is instantiated with the _aliased_ configuration,
   286  # so any AWS resources it defines will use the us-west-2 region.
   287  module "example" {
   288    source    = "./example"
   289    providers = {
   290      aws = "aws.usw2"
   291    }
   292  }
   293  ```
   294  
   295  The `providers` argument within a `module` block is similar to
   296  the `provider` argument within a resource as described for
   297  [multiple provider instances](/docs/configuration/providers.html#multiple-provider-instances),
   298  but is a map rather than a single string because a module may contain resources
   299  from many different providers.
   300  
   301  Once the `providers` argument is used in a `module` block, it overrides all of
   302  the default inheritance behavior, so it is necessary to enumerate mappings
   303  for _all_ of the required providers. This is to avoid confusion and surprises
   304  that may result when mixing both implicit and explicit provider passing.
   305  
   306  Additional provider configurations (those with the `alias` argument set) are
   307  _never_ inherited automatically by child modules, and so must always be passed
   308  explicitly using the `providers` map. For example, a module
   309  that configures connectivity between networks in two AWS regions is likely
   310  to need both a source and a destination region. In that case, the root module
   311  may look something like this:
   312  
   313  ```hcl
   314  provider "aws" {
   315    alias  = "usw1"
   316    region = "us-west-1"
   317  }
   318  
   319  provider "aws" {
   320    alias  = "usw2"
   321    region = "us-west-2"
   322  }
   323  
   324  module "tunnel" {
   325    source    = "./tunnel"
   326    providers = {
   327      aws.src = "aws.usw1"
   328      aws.dst = "aws.usw2"
   329    }
   330  }
   331  ```
   332  
   333  In the `providers` map, the keys are provider names as expected by the child
   334  module, while the values are the names of corresponding configurations in
   335  the _current_ module. The subdirectory `./tunnel` must then contain
   336  _proxy configuration blocks_ like the following, to declare that it
   337  requires configurations to be passed with these from the `providers` block in
   338  the parent's `module` block:
   339  
   340  ```hcl
   341  provider "aws" {
   342    alias = "src"
   343  }
   344  
   345  provider "aws" {
   346    alias = "dst"
   347  }
   348  ```
   349  
   350  Each resource should then have its own `provider` attribute set to either
   351  `"aws.src"` or `"aws.dst"` to choose which of the two provider instances to use.
   352  
   353  A proxy configuration block is one that is either completely empty or that
   354  contains only the `alias` argument. It serves as a placeholder for
   355  provider configurations passed between modules. Although an empty proxy
   356  configuration block is valid, it is not necessary: proxy configuration blocks
   357  are needed only to establish which _alias_ provider configurations a child
   358  module is expecting.
   359  
   360  A proxy configuration block must not include the `version` argument. To specify
   361  version constraints for a particular child module without creating a local
   362  module configuration, use the [`required_providers`](/docs/configuration/terraform.html#specifying-required-provider-versions)
   363  setting inside a `terraform` block.
   364  
   365  ## Multiple Instances of a Module
   366  
   367  A particular module source can be instantiated multiple times:
   368  
   369  ```hcl
   370  # my_buckets.tf
   371  
   372  module "assets_bucket" {
   373    source = "./publish_bucket"
   374    name   = "assets"
   375  }
   376  
   377  module "media_bucket" {
   378    source = "./publish_bucket"
   379    name   = "media"
   380  }
   381  ```
   382  
   383  ```hcl
   384  # publish_bucket/bucket-and-cloudfront.tf
   385  
   386  variable "name" {} # this is the input parameter of the module
   387  
   388  resource "aws_s3_bucket" "example" {
   389    # ...
   390  }
   391  
   392  resource "aws_iam_user" "deploy_user" {
   393    # ...
   394  }
   395  ```
   396  
   397  This example defines a local child module in the `./publish_bucket`
   398  subdirectory. That module has configuration to create an S3 bucket. The module
   399  wraps the bucket and all the other implementation details required to configure
   400  a bucket.
   401  
   402  We can then instantiate the module multiple times in our configuration by
   403  giving each instance a unique name -- here `module "assets_bucket"` and
   404  `module "media_bucket"` -- whilst specifying the same `source` value.
   405  
   406  Resources from child modules are prefixed with `module.<module-instance-name>`
   407  when displayed in plan output and elsewhere in the UI. For example, the
   408  `./publish_bucket` module contains `aws_s3_bucket.example`, and so the two
   409  instances of this module produce S3 bucket resources with [_resource addresses_](/docs/internals/resource-addressing.html)
   410  `module.assets_bucket.aws_s3_bucket.example` and `module.media_bucket.aws_s3_bucket.example`
   411  respectively. These full addresses are used within the UI and on the command
   412  line, but are not valid within interpolation expressions due to the
   413  encapsulation behavior described above.
   414  
   415  When refactoring an existing configuration to introduce modules, moving
   416  resource blocks between modules causes Terraform to see the new location
   417  as an entirely separate resource to the old. Always check the execution plan
   418  after performing such actions to ensure that no resources are surprisingly
   419  deleted.
   420  
   421  Each instance of a module may optionally have different providers passed to it
   422  using the `providers` argument described above. This can be useful in situations
   423  where, for example, a duplicated set of resources must be created across
   424  several regions or datacenters.
   425  
   426  ## Tainting resources within a module
   427  
   428  The [taint command](/docs/commands/taint.html) can be used to _taint_ specific
   429  resources within a module:
   430  
   431  ```shell
   432  $ terraform taint -module=salt_master aws_instance.salt_master
   433  ```
   434  
   435  It is not possible to taint an entire module. Instead, each resource within
   436  the module must be tainted separately.