github.com/wikibal01/hashicorp-terraform@v0.11.12-beta1/website/intro/getting-started/modules.html.md (about)

     1  ---
     2  layout: "intro"
     3  page_title: "Modules"
     4  sidebar_current: "gettingstarted-modules"
     5  description: |-
     6    Up to this point, we've been configuring Terraform by editing Terraform configurations directly. As our infrastructure grows, this practice has a few key problems: a lack of organization, a lack of reusability, and difficulties in management for teams.
     7  ---
     8  
     9  # Modules
    10  
    11  Up to this point, we've been configuring Terraform by editing Terraform
    12  configurations directly. As our infrastructure grows, this practice has a few
    13  key problems: a lack of organization, a lack of reusability, and difficulties
    14  in management for teams.
    15  
    16  _Modules_ in Terraform are self-contained packages of Terraform configurations
    17  that are managed as a group. Modules are used to create reusable components,
    18  improve organization, and to treat pieces of infrastructure as a black box.
    19  
    20  This section of the getting started will cover the basics of using modules.
    21  Writing modules is covered in more detail in the
    22  [modules documentation](/docs/modules/index.html).
    23  
    24  ~> **Warning!** The examples on this page are _**not** eligible_ for
    25  [the AWS free tier](https://aws.amazon.com/free/). Do not try the examples
    26  on this page unless you're willing to spend a small amount of money.
    27  
    28  ## Using Modules
    29  
    30  If you have any instances running from prior steps in the getting
    31  started guide, use `terraform destroy` to destroy them, and remove all
    32  configuration files.
    33  
    34  The [Terraform Registry](https://registry.terraform.io/) includes a directory
    35  of ready-to-use modules for various common purposes, which can serve as
    36  larger building-blocks for your infrastructure.
    37  
    38  In this example, we're going to use
    39  [the Consul Terraform module for AWS](https://registry.terraform.io/modules/hashicorp/consul/aws),
    40  which will set up a complete [Consul](https://www.consul.io) cluster.
    41  This and other modules can be found via the search feature on the Terraform
    42  Registry site.
    43  
    44  Create a configuration file with the following contents:
    45  
    46  ```hcl
    47  provider "aws" {
    48    access_key = "AWS ACCESS KEY"
    49    secret_key = "AWS SECRET KEY"
    50    region     = "us-east-1"
    51  }
    52  
    53  module "consul" {
    54    source = "hashicorp/consul/aws"
    55  
    56    num_servers = "3"
    57  }
    58  ```
    59  
    60  The `module` block begins with the example given on the Terraform Registry
    61  page for this module, telling Terraform to create and manage this module.
    62  This is similar to a `resource` block: it has a name used within this
    63  configuration -- in this case, `"consul"` -- and a set of input values
    64  that are listed in
    65  [the module's "Inputs" documentation](https://registry.terraform.io/modules/hashicorp/consul/aws?tab=inputs).
    66  
    67  (Note that the `provider` block can be omitted in favor of environment
    68  variables. See the [AWS Provider docs](/docs/providers/aws/index.html)
    69  for details.  This module requires that your AWS account has a default VPC.)
    70  
    71  The `source` attribute is the only mandatory argument for modules. It tells
    72  Terraform where the module can be retrieved. Terraform automatically
    73  downloads and manages modules for you.
    74  
    75  In this case, the module is retrieved from the official Terraform Registry.
    76  Terraform can also retrieve modules from a variety of sources, including
    77  private module registries or directly from Git, Mercurial, HTTP, and local
    78  files.
    79  
    80  The other attributes shown are inputs to our module. This module supports many
    81  additional inputs, but all are optional and have reasonable values for
    82  experimentation.
    83  
    84  After adding a new module to configuration, it is necessary to run (or re-run)
    85  `terraform init` to obtain and install the new module's source code:
    86  
    87  ```
    88  $ terraform init
    89  # ...
    90  ```
    91  
    92  By default, this command does not check for new module versions that may be
    93  available, so it is safe to run multiple times. The `-upgrade` option will
    94  additionally check for any newer versions of existing modules and providers
    95  that may be available.
    96  
    97  ## Apply Changes
    98  
    99  With the Consul module (and its dependencies) installed, we can now apply
   100  these changes to create the resources described within.
   101  
   102  If you run `terraform apply`, you will see a large list of all of the
   103  resources encapsulated in the module. The output is similar to what we
   104  saw when using resources directly, but the resource names now have
   105  module paths prefixed to their names, like in the following example:
   106  
   107  ```
   108    + module.consul.module.consul_clients.aws_autoscaling_group.autoscaling_group
   109        id:                                        <computed>
   110        arn:                                       <computed>
   111        default_cooldown:                          <computed>
   112        desired_capacity:                          "6"
   113        force_delete:                              "false"
   114        health_check_grace_period:                 "300"
   115        health_check_type:                         "EC2"
   116        launch_configuration:                      "${aws_launch_configuration.launch_configuration.name}"
   117        max_size:                                  "6"
   118        metrics_granularity:                       "1Minute"
   119        min_size:                                  "6"
   120        name:                                      <computed>
   121        protect_from_scale_in:                     "false"
   122        tag.#:                                     "2"
   123        tag.2151078592.key:                        "consul-clients"
   124        tag.2151078592.propagate_at_launch:        "true"
   125        tag.2151078592.value:                      "consul-example"
   126        tag.462896764.key:                         "Name"
   127        tag.462896764.propagate_at_launch:         "true"
   128        tag.462896764.value:                       "consul-example-client"
   129        termination_policies.#:                    "1"
   130        termination_policies.0:                    "Default"
   131        vpc_zone_identifier.#:                     "6"
   132        vpc_zone_identifier.1880739334:            "subnet-5ce4282a"
   133        vpc_zone_identifier.3458061785:            "subnet-16600f73"
   134        vpc_zone_identifier.4176925006:            "subnet-485abd10"
   135        vpc_zone_identifier.4226228233:            "subnet-40a9b86b"
   136        vpc_zone_identifier.595613151:             "subnet-5131b95d"
   137        vpc_zone_identifier.765942872:             "subnet-595ae164"
   138        wait_for_capacity_timeout:                 "10m"
   139  ```
   140  
   141  The `module.consul.module.consul_clients` prefix shown above indicates
   142  not only that the resource is from the `module "consul"` block we wrote,
   143  but in fact that this module has its own `module "consul_clients"` block
   144  within it. Modules can be nested to decompose complex systems into
   145  manageable components.
   146  
   147  The full set of resources created by this module includes an autoscaling group,
   148  security groups, IAM roles and other individual resources that all support
   149  the Consul cluster that will be created.
   150  
   151  Note that as we warned above, the resources created by this module are
   152  not eligible for the AWS free tier and so proceeding further will have some
   153  cost associated. To proceed with the creation of the Consul cluster, type
   154  `yes` at the confirmation prompt.
   155  
   156  ```
   157  # ...
   158  
   159  module.consul.module.consul_clients.aws_security_group.lc_security_group: Creating...
   160    description:            "" => "Security group for the consul-example-client launch configuration"
   161    egress.#:               "" => "<computed>"
   162    ingress.#:              "" => "<computed>"
   163    name:                   "" => "<computed>"
   164    name_prefix:            "" => "consul-example-client"
   165    owner_id:               "" => "<computed>"
   166    revoke_rules_on_delete: "" => "false"
   167    vpc_id:                 "" => "vpc-22099946"
   168  
   169  # ...
   170  
   171  Apply complete! Resources: 34 added, 0 changed, 0 destroyed.
   172  ```
   173  
   174  After several minutes and many log messages about all of the resources
   175  being created, you'll have a three-server Consul cluster up and running.
   176  Without needing any knowledge of how Consul works, how to install Consul,
   177  or how to form a Consul cluster, you've created a working cluster in just
   178  a few minutes.
   179  
   180  ## Module Outputs
   181  
   182  Just as the module instance had input arguments such as `num_servers` above,
   183  module can also produce _output_ values, similar to resource attributes.
   184  
   185  [The module's outputs reference](https://registry.terraform.io/modules/hashicorp/consul/aws?tab=outputs)
   186  describes all of the different values it produces. Overall, it exposes the
   187  id of each of the resources it creates, as well as echoing back some of the
   188  input values.
   189  
   190  One of the supported outputs is called `asg_name_servers`, and its value
   191  is the name of the auto-scaling group that was created to manage the Consul
   192  servers.
   193  
   194  To reference this, we'll just put it into our _own_ output value. This
   195  value could actually be used anywhere: in another resource, to configure
   196  another provider, etc.
   197  
   198  Add the following to the end of the existing configuration file created
   199  above:
   200  
   201  ```hcl
   202  output "consul_server_asg_name" {
   203    value = "${module.consul.asg_name_servers}"
   204  }
   205  ```
   206  
   207  The syntax for referencing module outputs is `${module.NAME.OUTPUT}`, where
   208  `NAME` is the module name given in the header of the `module` configuration
   209  block and `OUTPUT` is the name of the output to reference.
   210  
   211  If you run `terraform apply` again, Terraform will make no changes to
   212  infrastructure, but you'll now see the "consul\_server\_asg\_name" output with
   213  the name of the created auto-scaling group:
   214  
   215  ```
   216  # ...
   217  
   218  Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
   219  
   220  Outputs:
   221  
   222  consul_server_asg_name = tf-asg-2017103123350991200000000a
   223  ```
   224  
   225  If you look in the Auto-scaling Groups section of the EC2 console you should
   226  find an autoscaling group of this name, and from there find the three
   227  Consul servers it is running. (If you can't find it, make sure you're looking
   228  in the right region!)
   229  
   230  ## Destroy
   231  
   232  Just as with top-level resources, we can destroy the resources created by
   233  the Consul module to avoid ongoing costs:
   234  
   235  ```
   236  $ terraform destroy
   237  # ...
   238  
   239  Terraform will perform the following actions:
   240  
   241    - module.consul.module.consul_clients.aws_autoscaling_group.autoscaling_group
   242  
   243    - module.consul.module.consul_clients.aws_iam_instance_profile.instance_profile
   244  
   245    - module.consul.module.consul_clients.aws_iam_role.instance_role
   246  
   247  # ...
   248  ```
   249  
   250  As usual, Terraform describes all of the actions it will take. In this case,
   251  it plans to destroy all of the resources that were created by the module.
   252  Type `yes` to confirm and, after a few minutes and even more log output,
   253  all of the resources should be destroyed:
   254  
   255  ```
   256  Destroy complete! Resources: 34 destroyed.
   257  ```
   258  
   259  With all of the resources destroyed, you can delete the configuration file
   260  we created above. We will not make any further use of it, and so this avoids
   261  the risk of accidentally re-creating the Consul cluster.
   262  
   263  ## Next
   264  
   265  For more information on modules, the types of sources supported, how
   266  to write modules, and more, read the in-depth
   267  [module documentation](/docs/modules/index.html).
   268  
   269  Next, we learn about [Terraform's remote collaboration features](/intro/getting-started/remote.html).