Learning Objectives
By the end of this chapter, you will be able to:
- Differentiate between
resourceanddatablocks and pick the correct one for read versus write intent. - Build cross-resource references using attribute paths and produce a clean implicit dependency graph.
- Declare input
variable,output, andlocalsblocks at the right scope with correct precedence and sensitivity rules. - Use complex collection types (list, set, map, object, tuple) and conversion functions to model real configuration shape.
- Write dynamic configuration using expressions, functions, splat operators, the conditional operator, and
dynamicblocks. - Express resource dependencies through implicit references and the explicit
depends_onmeta-argument when the graph is incomplete. - Validate inputs and module assumptions with
validation,precondition,postcondition, andcheckblocks. - Manage sensitive data using
sensitive = true, thevaultprovider, and ephemeral-style patterns that keep secrets out of state and logs.
Executive Summary
resourceblocks own a real object's lifecycle;datablocks read existing state without mutating it, and the working-directory configuration is the sum of both kinds of blocks plus the references between them.- Cross-resource references like
aws_vpc.main.idbuild the dependency graph for free; explicitdepends_onis reserved for relationships that are real at the API level but invisible to HCL. - Variables capture inputs with a type, default, and validation contract; outputs capture results for the user, the parent module, or remote-state consumers;
localscapture derived values that should be computed exactly once. - Complex types (list, set, map, object, tuple) carry intent into the type system, and the dynamic construct family (
forexpressions, splats, conditional,dynamicblocks, function calls) reshapes those values into the literal block structure the providers require. - Custom conditions move bug-detection from
applytime toplantime, and thesensitiveflag plus thevaultprovider keep secret material out of console output and version control even when it must still pass through state.
Assumptions
- Examples use a generic mix of providers (
random,local,null, plus an illustrative cloud provider) so that the configuration patterns translate across AWS, Azure, Google Cloud, and on-premises targets. - The reader has already worked through provider declaration, the dependency lock file, the core write/plan/apply workflow, and the
terraform.tfstatemodel from the previous chapters; those terms are reused without redefinition. - Resource names, identifiers, and CIDR blocks in code samples are illustrative only; the goal is to show the configuration shape, not a production-ready deployment.
- All command-line output is rendered in a neutral form that matches the Terraform 1.12 CLI; older 0.12-style interpolation syntax (
"${var.x}"around bare references) is shown only when it appears as a banned-distractor anti-pattern.
