github.com/hs0210/hashicorp-terraform@v0.11.12-beta1/website/docs/modules/usage.html.markdown (about)

     1  ---
     2  layout: "docs"
     3  page_title: "Using Modules"
     4  sidebar_current: "docs-modules-usage"
     5  description: Using modules in Terraform is very similar to defining resources.
     6  ---
     7  
     8  # Module Usage
     9  
    10  Using child modules in Terraform is very similar to defining resources:
    11  
    12  ```shell
    13  module "consul" {
    14    source  = "hashicorp/consul/aws"
    15    servers = 3
    16  }
    17  ```
    18  
    19  You can view the full documentation for configuring modules in the [Module Configuration](/docs/configuration/modules.html) section.
    20  
    21  In modules we only specify a name, rather than a name and a type as for resources.
    22  This name is used elsewhere in the configuration to reference the module and
    23  its outputs.
    24  
    25  The source tells Terraform what to create. In this example, we instantiate
    26  the [Consul module for AWS](https://registry.terraform.io/modules/hashicorp/consul/aws)
    27  from the [Terraform Registry](https://registry.terraform.io). Other source
    28  types are supported, as described in the following section.
    29  
    30  Just like a resource, a module's configuration can be deleted to destroy the
    31  resources belonging to the module.
    32  
    33  ## Source
    34  
    35  The only required configuration key for a module is the `source` parameter. The
    36  value of this tells Terraform where to download the module's source code.
    37  Terraform comes with support for a variety of module sources.
    38  
    39  We recommend using modules from the public [Terraform Registry](/docs/registry/index.html)
    40  or from [Terraform Enterprise's private module registry](/docs/enterprise/registry/index.html).
    41  These sources support version constraints for a more reliable experience, and
    42  provide a searchable marketplace for finding the modules you need.
    43  
    44  Registry modules are specified using a simple slash-separated path like the
    45  `hashicorp/consul/aws` path used in the above example. The full source string
    46  for each registry module can be found from the registry website.
    47  
    48  Terraform also supports modules in local directories, identified by a relative
    49  path starting with either `./` or `../`. Such local modules are useful to
    50  organize code in more complex repositories, and are described in more detail
    51  in [_Creating Modules_](/docs/modules/create.html).
    52  
    53  Finally, Terraform can download modules directly from various storage providers
    54  and version control systems. These sources do not support versioning and other
    55  registry benefits, but can be convenient for getting started when already
    56  available within an organization. The full list of available sources
    57  are documented in [the module sources documentation](/docs/modules/sources.html).
    58  
    59  When a configuration uses modules, they must first be installed by running
    60  [`terraform init`](/docs/commands/init.html):
    61  
    62  ```shell
    63  $ terraform init
    64  ```
    65  
    66  This command will download any modules that haven't been updated already,
    67  as well as performing other Terraform working directory initialization such
    68  as installing providers.
    69  
    70  By default the command will not check for available updates to already-installed
    71  modules, but you can use the `-upgrade` option to check for available upgrades.
    72  When version constraints are specified (as described in the following section)
    73  a newer version will be used only if it is within the given constraint.
    74  
    75  ## Module Versions
    76  
    77  We recommend explicitly constraining the acceptable version numbers for
    78  each external module to avoid unexpected or unwanted changes.
    79  
    80  Use the `version` attribute in the `module` block to specify versions:
    81  
    82  ```shell
    83  module "consul" {
    84    source  = "hashicorp/consul/aws"
    85    version = "0.0.5"
    86  
    87    servers = 3
    88  }
    89  ```
    90  
    91  The `version` attribute value may either be a single explicit version or
    92  a version constraint expression. Constraint expressions use the following
    93  syntax to specify a _range_ of versions that are acceptable:
    94  
    95  * `>= 1.2.0`: version 1.2.0 or newer
    96  * `<= 1.2.0`: version 1.2.0 or older
    97  * `~> 1.2.0`: any non-beta version `>= 1.2.0` and `< 1.3.0`, e.g. `1.2.X`
    98  * `~> 1.2`: any non-beta version `>= 1.2.0` and `< 2.0.0`, e.g. `1.X.Y`
    99  * `>= 1.0.0, <= 2.0.0`: any version between 1.0.0 and 2.0.0 inclusive
   100  
   101  When depending on third-party modules, references to specific versions are
   102  recommended since this ensures that updates only happen when convenient to you.
   103  
   104  For modules maintained within your organization, a version range strategy
   105  may be appropriate if a semantic versioning methodology is used consistently
   106  or if there is a well-defined release process that avoids unwanted updates.
   107  
   108  Version constraints are supported only for modules installed from a module
   109  registry, such as the [Terraform Registry](https://registry.terraform.io/) or
   110  [Terraform Enterprise's private module registry](/docs/enterprise/registry/index.html).
   111  Other module sources can provide their own versioning mechanisms within the
   112  source string itself, or might not support versions at all. In particular,
   113  modules sourced from local file paths do not support `version`; since
   114  they're loaded from the same source repository, they always share the same
   115  version as their caller.
   116  
   117  ## Configuration
   118  
   119  The arguments used in a `module` block, such as the `servers` parameter above,
   120  correspond to [variables](/docs/configuration/variables.html) within the module
   121  itself. You can therefore discover all the available variables for a module by
   122  inspecting the source of it.
   123  
   124  The special arguments `source`, `version` and `providers` are exceptions. These
   125  are used for special purposes by Terraform and should therefore not be used
   126  as variable names within a module.
   127  
   128  ## Outputs
   129  
   130  Modules encapsulate their resources. A resource in one module cannot directly depend on resources or attributes in other modules, unless those are exported through [outputs](/docs/configuration/outputs.html). These outputs can be referenced in other places in your configuration, for example:
   131  
   132  ```hcl
   133  resource "aws_instance" "client" {
   134    ami               = "ami-408c7f28"
   135    instance_type     = "t1.micro"
   136    availability_zone = "${module.consul.server_availability_zone}"
   137  }
   138  ```
   139  
   140  This is deliberately very similar to accessing resource attributes. Instead of
   141  referencing a resource attribute, however, the expression in this case
   142  references an output of the module.
   143  
   144  Just like with resources, interpolation expressions can create implicit
   145  dependencies on resources and other modules. Since modules encapsulate
   146  other resources, however, the dependency is not on the module as a whole
   147  but rather on the `server_availability_zone` output specifically, which
   148  allows Terraform to work on resources in different modules concurrently rather
   149  than waiting for the entire module to be complete before proceeding.
   150  
   151  ## Providers within Modules
   152  
   153  In a configuration with multiple modules, there are some special considerations
   154  for how resources are associated with provider configurations.
   155  
   156  While in principle `provider` blocks can appear in any module, it is recommended
   157  that they be placed only in the _root_ module of a configuration, since this
   158  approach allows users to configure providers just once and re-use them across
   159  all descendent modules.
   160  
   161  Each resource in the configuration must be associated with one provider
   162  configuration, which may either be within the same module as the resource
   163  or be passed from the parent module. Providers can be passed down to descendent
   164  modules in two ways: either _implicitly_ through inheritance, or _explicitly_
   165  via the `providers` argument within a `module` block. These two options are
   166  discussed in more detail in the following sections.
   167  
   168  In all cases it is recommended to keep explicit provider configurations only in
   169  the root module and pass them (whether implicitly or explicitly) down to
   170  descendent modules. This avoids the provider configurations from being "lost"
   171  when descendent modules are removed from the configuration. It also allows
   172  the user of a configuration to determine which providers require credentials
   173  by inspecting only the root module.
   174  
   175  Provider configurations are used for all operations on associated resources,
   176  including destroying remote objects and refreshing state. Terraform retains, as
   177  part of its state, a reference to the provider configuration that was most
   178  recently used to apply changes to each resource. When a `resource` block is
   179  removed from the configuration, this record in the state is used to locate the
   180  appropriate configuration because the resource's `provider` argument (if any)
   181  is no longer present in the configuration.
   182  
   183  As a consequence, it is required that all resources created for a particular
   184  provider configuration must be destroyed before that provider configuration is
   185  removed, unless the related resources are re-configured to use a different
   186  provider configuration first.
   187  
   188  ### Implicit Provider Inheritance
   189  
   190  For convenience in simple configurations, a child module automatically inherits
   191  default (un-aliased) provider configurations from its parent. This means that
   192  explicit `provider` blocks appear only in the root module, and downstream
   193  modules can simply declare resources for that provider and have them
   194  automatically associated with the root provider configurations.
   195  
   196  For example, the root module might contain only a `provider` block and a
   197  `module` block to instantiate a child module:
   198  
   199  ```hcl
   200  provider "aws" {
   201    region = "us-west-1"
   202  }
   203  
   204  module "child" {
   205    source = "./child"
   206  }
   207  ```
   208  
   209  The child module can then use any resource from this provider with no further
   210  provider configuration required:
   211  
   212  ```hcl
   213  resource "aws_s3_bucket" "example" {
   214    bucket = "provider-inherit-example"
   215  }
   216  ```
   217  
   218  This approach is recommended in the common case where only a single
   219  configuration is needed for each provider across the entire configuration.
   220  
   221  In more complex situations there may be [multiple provider instances](/docs/configuration/providers.html#multiple-provider-instances),
   222  or a child module may need to use different provider settings than
   223  its parent. For such situations, it's necessary to pass providers explicitly
   224  as we will see in the next section.
   225  
   226  ## Passing Providers Explicitly
   227  
   228  When child modules each need a different configuration of a particular
   229  provider, or where the child module requires a different provider configuration
   230  than its parent, the `providers` argument within a `module` block can be
   231  used to define explicitly which provider configs are made available to the
   232  child module. For example:
   233  
   234  ```hcl
   235  # The default "aws" configuration is used for AWS resources in the root
   236  # module where no explicit provider instance is selected.
   237  provider "aws" {
   238    region = "us-west-1"
   239  }
   240  
   241  # A non-default, or "aliased" configuration is also defined for a different
   242  # region.
   243  provider "aws" {
   244    alias  = "usw2"
   245    region = "us-west-2"
   246  }
   247  
   248  # An example child module is instantiated with the _aliased_ configuration,
   249  # so any AWS resources it defines will use the us-west-2 region.
   250  module "example" {
   251    source    = "./example"
   252    providers = {
   253      aws = "aws.usw2"
   254    }
   255  }
   256  ```
   257  
   258  The `providers` argument within a `module` block is similar to
   259  the `provider` argument within a resource as described for
   260  [multiple provider instances](/docs/configuration/providers.html#multiple-provider-instances),
   261  but is a map rather than a single string because a module may contain resources
   262  from many different providers.
   263  
   264  Once the `providers` argument is used in a `module` block, it overrides all of
   265  the default inheritance behavior, so it is necessary to enumerate mappings
   266  for _all_ of the required providers. This is to avoid confusion and surprises
   267  that may result when mixing both implicit and explicit provider passing.
   268  
   269  Additional provider configurations (those with the `alias` argument set) are
   270  _never_ inherited automatically by child modules, and so must always be passed
   271  explicitly using the `providers` map. For example, a module
   272  that configures connectivity between networks in two AWS regions is likely
   273  to need both a source and a destination region. In that case, the root module
   274  may look something like this:
   275  
   276  ```hcl
   277  provider "aws" {
   278    alias  = "usw1"
   279    region = "us-west-1"
   280  }
   281  
   282  provider "aws" {
   283    alias  = "usw2"
   284    region = "us-west-2"
   285  }
   286  
   287  module "tunnel" {
   288    source    = "./tunnel"
   289    providers = {
   290      aws.src = "aws.usw1"
   291      aws.dst = "aws.usw2"
   292    }
   293  }
   294  ```
   295  
   296  In the `providers` map, the keys are provider names as expected by the child
   297  module, while the values are the names of corresponding configurations in
   298  the _current_ module. The subdirectory `./tunnel` must then contain
   299  _proxy configuration blocks_ like the following, to declare that it
   300  requires configurations to be passed with these from the `providers` block in
   301  the parent's `module` block:
   302  
   303  ```hcl
   304  provider "aws" {
   305    alias = "src"
   306  }
   307  
   308  provider "aws" {
   309    alias = "dst"
   310  }
   311  ```
   312  
   313  Each resource should then have its own `provider` attribute set to either
   314  `"aws.src"` or `"aws.dst"` to choose which of the two provider instances to use.
   315  
   316  At this time it is required to write an explicit proxy configuration block
   317  even for default (un-aliased) provider configurations when they will be passed
   318  via an explicit `providers` block:
   319  
   320  ```hcl
   321  provider "aws" {
   322  }
   323  ```
   324  
   325  If such a block is not present, the child module will behave as if it has no
   326  configurations of this type at all, which may cause input prompts to supply
   327  any required provider configuration arguments. This limitation will be
   328  addressed in a future version of Terraform.
   329  
   330  ## Multiple Instances of a Module
   331  
   332  A particular module source can be instantiated multiple times:
   333  
   334  ```hcl
   335  # my_buckets.tf
   336  
   337  module "assets_bucket" {
   338    source = "./publish_bucket"
   339    name   = "assets"
   340  }
   341  
   342  module "media_bucket" {
   343    source = "./publish_bucket"
   344    name   = "media"
   345  }
   346  ```
   347  
   348  ```hcl
   349  # publish_bucket/bucket-and-cloudfront.tf
   350  
   351  variable "name" {} # this is the input parameter of the module
   352  
   353  resource "aws_s3_bucket" "example" {
   354    # ...
   355  }
   356  
   357  resource "aws_iam_user" "deploy_user" {
   358    # ...
   359  }
   360  ```
   361  
   362  This example defines a local child module in the `./publish_bucket`
   363  subdirectory. That module has configuration to create an S3 bucket. The module
   364  wraps the bucket and all the other implementation details required to configure
   365  a bucket.
   366  
   367  We can then instantiate the module multiple times in our configuration by
   368  giving each instance a unique name -- here `module "assets_bucket"` and
   369  `module "media_bucket"` -- whilst specifying the same `source` value.
   370  
   371  Resources from child modules are prefixed with `module.<module-instance-name>`
   372  when displayed in plan output and elsewhere in the UI. For example, the
   373  `./publish_bucket` module contains `aws_s3_bucket.example`, and so the two
   374  instances of this module produce S3 bucket resources with [_resource addresses_](/docs/internals/resource-addressing.html)
   375  `module.assets_bucket.aws_s3_bucket.example` and `module.media_bucket.aws_s3_bucket.example`
   376  respectively. These full addresses are used within the UI and on the command
   377  line, but are not valid within interpolation expressions due to the
   378  encapsulation behavior described above.
   379  
   380  When refactoring an existing configuration to introduce modules, moving
   381  resource blocks between modules causes Terraform to see the new location
   382  as an entirely separate resource to the old. Always check the execution plan
   383  after performing such actions to ensure that no resources are surprisingly
   384  deleted.
   385  
   386  Each instance of a module may optionally have different providers passed to it
   387  using the `providers` argument described above. This can be useful in situations
   388  where, for example, a duplicated set of resources must be created across
   389  several regions or datacenters.
   390  
   391  ## Summarizing Modules in the UI
   392  
   393  By default, commands such as the [plan command](/docs/commands/plan.html) and
   394  [graph command](/docs/commands/graph.html) will show each resource in a nested
   395  module to represent the full scope of the configuration. For more complex
   396  configurations, the `-module-depth` option may be useful to summarize some or all
   397  of the modules as single objects.
   398  
   399  For example, with a configuration similar to what we've built above, the default
   400  graph output looks like the following:
   401  
   402  ![Terraform Expanded Module Graph](docs/module_graph_expand.png)
   403  
   404  If we instead set `-module-depth=0`, the graph will look like this:
   405  
   406  ![Terraform Module Graph](docs/module_graph.png)
   407  
   408  Other commands work similarly with modules. Note that `-module-depth` only
   409  affects how modules are presented in the UI; it does not affect how modules
   410  and their contained resources are processed by Terraform operations.
   411  
   412  ## Tainting resources within a module
   413  
   414  The [taint command](/docs/commands/taint.html) can be used to _taint_ specific
   415  resources within a module:
   416  
   417  ```shell
   418  $ terraform taint -module=salt_master aws_instance.salt_master
   419  ```
   420  
   421  It is not possible to taint an entire module. Instead, each resource within
   422  the module must be tainted separately.