Advanced Terraform · Module 01
Modules and Code Structure
Write Terraform that other people can reuse: small modules with clear inputs and outputs, pinned module and provider versions with a committed lock file, count, for_each, dynamic blocks and lifecycle rules, and typed variables with validation and pre/postconditions.
What you will learn
- Split a configuration into a root module and focused child modules with clear inputs and outputs
- Use registry, Git and local module sources with version constraints, and explain the dependency lock file
- Choose between count and for_each, generate nested blocks with dynamic, and control replacement with lifecycle
- Use type constraints, optional attributes, for expressions, validation blocks and pre/postconditions
- Use built-in functions for strings, collections, encoding, files and templates, IP ranges and type conversion
Lessons
- Designing Reusable Modules
A module is a folder of .tf files; the root module calls child modules, passes inputs as variables and reads their outputs.
- Module Sources, Versions and the Lock File
Modules come from local paths, the registry or Git; pin them with version constraints or refs, and commit .terraform.lock.hcl so every run uses the same provider builds.
- count, for_each, dynamic Blocks and lifecycle
Create many instances with count or for_each (prefer for_each for anything keyed), generate nested blocks with dynamic, and control replacement with lifecycle.
- Types, Expressions and Validation
Typed variables with optional attributes, locals and for expressions keep code short; validation blocks and pre/postconditions turn bad input into clear errors.
- Built-in Functions
Terraform has no user-defined functions, but more than a hundred built-ins: strings, collections, encoding, files and templates, IP networks, type conversion, dates and hashes, plus functions shipped by providers.