Chuyển đến nội dung

Bài 24 · Modules

Designing Good Terraform Modules: Structure and Validation

Design Terraform modules that last: standard file layout, input validation, sensible defaults, composition over nesting, versioned interfaces and documentation habits.

Writing a module is easy; writing one that other people can use for years without surprises is a craft. Most module pain comes from the same few mistakes: too many inputs, hidden assumptions, deeply nested calls and interfaces that change in every release. This lesson gives you a set of design rules, each with an example.

Standard layout

HashiCorp's recommended structure is plain and predictable:

TEXT
modules/web-service/
  main.tf         # resources
  variables.tf    # inputs
  outputs.tf      # outputs
  versions.tf     # required_version and required_providers
  README.md       # purpose, inputs, outputs, example
  examples/
    basic/main.tf # a runnable example
  tests/
    basic.tftest.hcl

Splitting by purpose (iam.tf, network.tf) is fine once main.tf grows past a few hundred lines. A versions.tf that pins a minimum is kinder to callers than an exact pin:

HCL
terraform {
  required_version = ">= 1.6"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = ">= 5.0, < 7.0"
    }
  }
}

Validate inputs early

A variable can reject bad values before any API call. Errors appear at plan time, in your own words:

HCL
variable "environment" {
  type        = string
  description = "Deployment environment."

  validation {
    condition     = contains(["dev", "staging", "prod"], var.environment)
    error_message = "environment must be dev, staging or prod."
  }
}

variable "cidr_block" {
  type = string

  validation {
    condition     = can(cidrhost(var.cidr_block, 0))
    error_message = "cidr_block must be valid CIDR notation, such as 10.0.0.0/16."
  }
}

can() turns an error into false, so it is the standard trick for format checks. Terraform 1.9 allows a validation to refer to other variables; before that it could only read its own.

Use typed objects with optional attributes for grouped settings:

HCL
variable "scaling" {
  type = object({
    min     = optional(number, 1)
    max     = optional(number, 4)
    cpu_pct = optional(number, 60)
  })
  default = {}
}

Callers can write scaling = { max = 10 } and the other fields take their defaults.

A validator you can run

The stand-in below mimics validation blocks: a list of rules, each with a condition and a message. It uses the same idea as can().

Python Variable validation

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Few inputs, good defaults

Ask yourself what a typical caller must decide. A web-service module should require a name and an image; instance size, health-check path and log retention can default. Avoid mirroring every argument of the underlying resource ("wrapper modules"): if callers need that many knobs, they should use the resource directly.

Two defaults that matter in practice:

  • Secure by default. Encryption on, public access off, deletion protection on for stateful resources.
  • Optional features as booleans or null. enable_logging = true or kms_key_arn = null; use count = var.enable_logging ? 1 : 0 or for_each over a conditional map inside the module.

Compose, do not nest

A module that calls a module that calls a module is hard to debug and creates long addresses (module.a.module.b.module.c.aws_x.y). Prefer composition: small modules that do one job, wired together in the root module.

HCL
module "network"  { source = "./modules/network" }
module "database" { source = "./modules/database"
                    subnet_ids = module.network.private_subnet_ids }
module "service"  { source = "./modules/web-service"
                    db_endpoint = module.database.endpoint }
flowchart TD
  subgraph Bad["Deep nesting"]
    A1["platform"] --> A2["app-stack"] --> A3["web-service"] --> A4["aws_ecs_service"]
  end
  subgraph Good["Composition in the root"]
    R["root"] --> N["network"]
    R --> D["database"]
    R --> S["web-service"]
    N --> D
    D --> S
  end

Flat composition keeps addresses short and dependencies visible.

A facade module that composes several others is still useful, for example a company-standard "service stack", but keep it to one level.

Keep the interface stable

Callers depend on your variable and output names. Treat them like a public API:

  • Adding an optional variable or an output is backward compatible.
  • Renaming, removing or changing the type of a variable is a breaking change: bump the major version and write migration notes.
  • Renaming a resource inside a module is breaking for state too, unless you ship a moved block (State Commands).
HCL
# inside the module, shipped with the release that renamed the resource
moved {
  from = aws_s3_bucket.bucket
  to   = aws_s3_bucket.this
}

Outputs, sensitive values and docs

Output only what callers need, and mark secrets:

HCL
output "db_password" {
  value     = random_password.db.result
  sensitive = true
}

Generate your README tables with terraform-docs so the inputs and outputs never drift from the code. Put an examples/ folder next to the module; it doubles as your integration test.

A quick lint of module interfaces

This stand-in checks a module description against some of the rules above: every variable has a description and a type, secrets are marked sensitive, and nothing is nested too deep.

Python Module interface linter

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Which function turns a failing expression into false, so it can be used in validation conditions?

    can() returns true if the expression evaluates without error.
  2. 2. Which change to a published module is breaking for callers?

    Callers pass the old name, so renaming (or removing) variables requires a major version.
  3. 3. Why prefer composition to deep nesting?

    Long address chains and hidden dependencies make nested modules hard to maintain.
  4. 4. How should a module expose a generated password?

    sensitive hides it from CLI output but the value remains in state.

Summary

  • Use the standard layout: main.tf, variables.tf, outputs.tf, versions.tf, README, examples.
  • Validate inputs with validation blocks, typed objects and optional() defaults.
  • Keep the required inputs few, and make defaults secure.
  • Compose small modules in the root instead of nesting deeply.
  • Treat variable and output names as a versioned public interface; ship moved blocks when renaming resources.

Next: Registry, Sources and Version Constraints

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.