HashiCorp - Terraform Associate Study Guide

    5: Terraform modules

    This chapter shows how Terraform packages reusable configuration into modules, where the binary fetches those modules from, how variables are scoped across the parent/child boundary, how inputs and outputs flow through a `module` block, and how the `version` argument constrains which release of a registry module a given working directory consumes. Every example is provider-agnostic so the patterns transfer to any cloud, on-premises, or service provider.

    Learning Objectives

    By the end of this chapter, you will be able to:

    • Explain how Terraform sources modules from local paths, the public Terraform Registry, and git repositories, including sub-directory references and ref pinning.
    • Describe variable scope within modules and the parent/child relationship, including why a child module cannot read a sibling or parent variable directly.
    • Use modules in configuration by wiring inputs through arguments on the module block and consuming outputs through the module.<name>.<output> reference syntax.
    • Manage module versions with the version argument, semver constraint operators, and explicit git refs, and recognise where each pinning mechanism is supported.

    Executive Summary

    • A module is any directory that holds Terraform configuration files; the directory you run terraform against is the root module, and every other module called from it is a child module.
    • The source argument on a module block tells Terraform where to fetch the child module from: a local path, the public Terraform Registry, a git repository over HTTPS or SSH, an HTTP archive, or an object store, with optional //subdir and ?ref= modifiers.
    • Variables are scoped per module. A child module only sees what the calling module passes in through arguments, and the calling module only sees what the child exposes through output blocks.
    • The version argument is honoured only for module sources that resolve through a registry (the public Terraform Registry or an HCP Terraform private registry). Git, local, and HTTP sources do not accept version; they are pinned through the source string itself.

    Assumptions

    • The reader is on Terraform 1.12 and uses the documented HCL syntax shipped with that release.
    • Provider configuration, state, and the core write/plan/apply loop are already established from earlier chapters; this chapter does not redefine provider, Terraform Core, the dependency lock file, or any term enumerated in the previous CONTEXT_OUTPUT blocks.
    • Examples avoid cloud-specific resources where possible. When a concrete provider is needed, the chapter uses a small set of generic providers (random, null, local) so the syntax is the focus, not the cloud surface area.

    Sections in this chapter

    1. Free
    2. Free with account
    3. Free with account
    4. Free with account
    5. Free with account