# Modules: reusable infrastructure

Stop copy-pasting: write a child module with inputs and outputs, call it several times, use a public module from the Terraform Registry, and version modules so upgrades are safe.

Course: [Terraform](https://devops.rajeev.pro/courses/terraform), lesson 10. About 30 minutes, intermediate. Source: https://devops.rajeev.pro/courses/terraform/10-modules

## What you will learn

- Explain root and child modules and when to write a module
- Build a module with variables, resources and outputs, and call it twice
- Read module outputs from the calling configuration
- Use a public module from the Terraform Registry and pin its version
- Version your own modules with Git tags and upgrade one environment at a time

> **Lab status.** **Verified lab:** the local module called twice and the cloudposse/label/null registry module. Run on Terraform 1.17.1; the output shown is real. <br />**Code walkthrough:** Git module sources and version tags: explained, not run. <br />**Cloud lab:** none; nothing here needs a cloud account.

## Why modules exist

Modules are how Terraform code grows past one folder without turning into copy-paste. It helps to
see what happens without them.

### The problem: one fix, three copies

A team builds a web stack in `dev/`. It works, so they copy the folder to `staging/` and `prod/`.
Months later, a security review says "encrypt the storage". They fix dev, then staging, and miss
prod, the one that mattered.

> **Figure.** Animated. Three folders, dev, staging and prod, each with a 300-line main.tf copied from the first. A fix, plus encryption equals true, appears in dev, then staging. Prod is marked forgot: still unencrypted.
>
> With copies, every fix has to be made in every copy.

### The fix: write it once, call it with different inputs

A **module** is a folder of Terraform code with inputs (variables) and outputs, like a function.
Each environment calls it with its own values, and a fix to the module reaches every caller.

> **Figure.** Animated. A module, modules/site, takes var.name and var.pages, contains local_file.page resources and outputs output.files. It is called three times: module shop with 3 pages, module blog with 1, module docs with 2. Each call produces its own pages: 3, 1 and 2 created.
>
> Inputs in, resources inside, outputs out.

### And then: versions, so a change doesn't hit production first

Once many configurations use a module, a change to it is a release. Each caller pins a version and
upgrades when it's ready: dev first, then staging, then prod.

> **Figure.** Animated. Module releases v1.2.0 and a new v1.3.0. dev and staging move to version 1.3.0 one after the other; prod stays on 1.2.0.
>
> Pinned versions turn a module change into a normal, staged release.

In this lesson you'll write a module, call it twice, use a real module from the Terraform Registry,
and pin versions.

## Root and child modules

Every Terraform configuration is a module. The folder you run `terraform plan` in is the **root
module**. A module it calls with a `module` block is a **child module**. A typical layout:

```text
project/
├── main.tf             # root module: calls the child modules
├── outputs.tf
└── modules/
    └── site/           # child module
        ├── main.tf
        ├── variables.tf
        └── outputs.tf
```

When to write a module: when the same group of resources appears in several places (a VPC, a
service with its load balancer and alarms), or to give other teams a safe, opinionated building
block. When not to: a module that wraps a single resource and passes every argument through adds a
layer and saves nothing.

## Module inputs and outputs

The child module from the lab creates one HTML file per page:

```hcl
# modules/site/variables.tf
variable "name" {
  description = "Site name, used in file names."
  type        = string
}

variable "pages" {
  description = "Page names to create."
  type        = list(string)
  default     = ["index"]
}
```

```hcl
# modules/site/main.tf
terraform {
  required_providers {
    local = {
      source  = "hashicorp/local"
      version = "~> 2.9"
    }
  }
}

resource "local_file" "page" {
  for_each = toset(var.pages)

  filename = "${path.root}/out/${var.name}/${each.key}.html"
  content  = "<h1>${var.name}: ${each.key}</h1>\n"
}
```

```hcl
# modules/site/outputs.tf
output "files" {
  description = "Paths of the pages this module created."
  value       = [for p in local_file.page : p.filename]
}
```

The module declares which providers it needs, but has **no `provider` block**: configuring providers
is the root module's job, and the child inherits them. `path.root` points at the root folder, so the
files land in one `out/` regardless of where the module lives.

The root calls it twice with different inputs:

```hcl
# main.tf
module "shop" {
  source = "./modules/site"
  name   = "shop"
  pages  = ["index", "cart", "checkout"]
}

module "blog" {
  source = "./modules/site"
  name   = "blog"
}

output "shop_files" {
  value = module.shop.files
}
```

Every module block needs `source`. The other arguments are the module's variables. `blog` doesn't
pass `pages`, so it gets the default `["index"]`. Outputs are read as `module.<name>.<output>`.

The resources get addresses that include the module, so the two calls never clash:

```sh
$ terraform state list
module.blog.local_file.page["index"]
module.shop.local_file.page["cart"]
module.shop.local_file.page["checkout"]
module.shop.local_file.page["index"]
$ find out -type f | sort
out/blog/index.html
out/shop/cart.html
out/shop/checkout.html
out/shop/index.html
```

## Registry modules

The Terraform Registry also hosts **modules**: thousands of them, including the widely used
`terraform-aws-modules` collection (VPC, EKS, RDS and more). The lab used `cloudposse/label/null`,
which builds consistent resource names and tags and needs no cloud account:

```hcl
module "label" {
  source    = "cloudposse/label/null"
  version   = "0.25.0"
  namespace = "acme"
  stage     = "prod"
  name      = "shop"
}

output "resource_name" {
  value = module.label.id
}

output "tags" {
  value = module.label.tags
}
```

A registry source has the form `namespace/name/provider`. `terraform init` downloads it:

```text
$ terraform init
Initializing the backend...

Initializing modules...
Downloading registry.terraform.io/cloudposse/label/null 0.25.0 for label...
- label in .terraform/modules/label
- shop in modules/site
- blog in modules/site
...
```

Local modules are used in place; registry modules are downloaded into `.terraform/modules`. The
outputs after apply:

```text
resource_name = "acme-prod-shop"
tags = tomap({
  "Name" = "acme-prod-shop"
  "Namespace" = "acme"
  "Stage" = "prod"
})
```

Before using a public module, check how often it's downloaded and updated, read its inputs, and read
its code. You're running someone else's infrastructure code with your credentials.

## Versioning modules

| Source             | Example                                                        | Pin with                                               |
| ------------------ | -------------------------------------------------------------- | ------------------------------------------------------ |
| Local path         | `./modules/site`                                               | Nothing: it's the same commit as the caller            |
| Terraform Registry | `cloudposse/label/null`                                        | `version = "0.25.0"` (constraints like `~> 0.25` work) |
| Git                | `git::https://github.com/acme/tf-modules.git//site?ref=v1.3.0` | `?ref=` a tag                                          |
| GitHub shorthand   | `github.com/acme/tf-modules//site?ref=v1.3.0`                  | `?ref=` a tag                                          |

The `//site` part points at a subfolder of the repository. The `version` argument only works for
registry sources; Git sources pin with `ref`, ideally an immutable tag.

For your own shared modules, the workflow looks like any library release:

1. Keep modules in their own repository, with a README and an `examples/` folder.
2. Release with semantic version tags: `v1.3.0`. A breaking input change is a major bump.
3. Each caller pins a tag and upgrades in a pull request: dev first, then staging, then prod.
4. Run `terraform init -upgrade` after changing a version, and read the plan.

> **In production.** Keep modules small and focused, with a clear set of inputs and outputs and sensible defaults. Don't configure providers inside them. When you restructure code into modules, use `moved` blocks (lesson 8) so existing resources move to their new addresses instead of being destroyed and recreated.

## Mission: Build a module and call it three times

Write modules/site with variables name and pages, a for_each local_file per page, and a files output. Call it for shop (3 pages), blog (default) and docs (2 pages), add cloudposse/label/null 0.25.0, and output each module's files and the label id.

- You need: An empty project
- You'll have: modules/site/

```sh
$ terraform init
$ terraform apply -auto-approve
$ terraform state list | wc -l
$ terraform output
```

You should see 6 page resources in state (3 + 1 + 2) and an id like `acme-prod-shop` from the label
module. If init says "Module not installed", you added a module block without re-running
`terraform init`.

## Try it

- Create `modules/site` with a variable, a resource and an output, and call it from main.tf.
- Call the same module a second time with different inputs and read the plan.
- Add `cloudposse/label/null` version 0.25.0 and run `terraform init`; find where it was downloaded.
- Read a module output with `terraform output`.
- Do the mini mission and keep `modules/site/`.

## Quiz

1. What is the root module?
   - A module from the Terraform Registry
   - **The folder where you run terraform plan and apply** (answer)
   - A module that runs as the root user
   Why: Every configuration is a module. The one you run commands in is the root; the modules it calls are child modules.

2. How does the calling configuration use a value created inside a child module?
   - It reads the module's resources directly, like module.site.local_file.page
   - **Through an output declared in the module, read as module.site.<output_name>** (answer)
   - Through a global variable
   Why: A module is a black box with inputs (variables) and outputs. Callers only see what it chooses to output.

3. Which source can use the version argument?
   - A local path like ./modules/site
   - **A registry module like cloudposse/label/null** (answer)
   - Any source
   Why: version only works for registry sources. For Git sources, pin with ?ref=v1.2.0 in the URL.

4. Why pin a module version in every caller?
   - It's required syntax
   - **So a new module release can't change production until you upgrade it there on purpose** (answer)
   - Pinning makes init faster
   Why: Unpinned modules change under you. Pinned versions let you upgrade dev, then staging, then prod, like any release.

## Resources

- [Modules overview](https://developer.hashicorp.com/terraform/language/modules) (HashiCorp)
- [Module sources (local, registry, Git)](https://developer.hashicorp.com/terraform/language/modules/sources) (HashiCorp)
- [Module development best practices](https://developer.hashicorp.com/terraform/language/modules/develop) (HashiCorp)
- [cloudposse/label/null on the Terraform Registry](https://registry.terraform.io/modules/cloudposse/label/null/latest) (Terraform Registry)
- [terraform-aws-modules (widely used AWS modules)](https://registry.terraform.io/namespaces/terraform-aws-modules) (Terraform Registry)
