Module 5: Terraform Modules

Lesson 5.3: Using Modules in Configuration

Calling a module

HCL
module "sites" {
  source   = "./modules/site" # meta-arguments first (style convention)
  for_each = var.sites

  name        = each.key # input variables of the child
  environment = each.value.environment
  pages       = each.value.pages
}

output "site_ids" {
  value = { for k, m in module.sites : k => m.site_id } # for_each module = map of instances
}

Module meta-arguments

Meta-argument Effect on modules
count / for_each Create multiple module instances, addressed as module.sites[0] or module.sites["blog"]. Available since 0.13.
providers Map of provider configurations to pass in, for example { aws = aws.west }. Default configurations are inherited automatically; aliased ones must be passed (Module 2).
depends_on Makes every object in the module wait on the listed objects. Use sparingly.

lifecycle isn't a module meta-argument. Set lifecycle rules on the resources inside the module.

Refactoring into a module with moved

When you move an existing resource into a module, its state address changes, for example from random_pet.blog to module.sites["blog"].random_pet.suffix. Without guidance, Terraform plans to destroy the old resource and create a new one. A moved block tells Terraform the object is the same:

HCL
moved {
  from = random_pet.blog
  to   = module.sites["blog"].random_pet.suffix
}

Module 6 covers moved in depth.

Standard module structure

Item Purpose
main.tf, variables.tf, outputs.tf Required by convention
versions.tf required_providers with >= minimum constraints
README.md Documents inputs and outputs. The registry renders it.
examples/ Example root configurations that call the module
modules/ Nested submodules
LICENSE Required for publishing

Public registry publishing requirements:

  • A public GitHub repo named terraform-<PROVIDER>-<NAME>, for example terraform-docker-site
  • The standard module structure
  • Semantic version tags, such as v1.0.0 or 1.0.0