Chapter Four

Variables, Outputs, and Expressions

How one configuration serves dev and prod through inputs, how it returns values to the world through outputs, and the HCL expressions, functions, and dynamic blocks that compute everything in between.

7 topics

A configuration that hardcodes every value is a configuration that serves exactly one environment. This chapter is about the parts that make a single config reusable: input variables that parameterize it, outputs that publish its results, locals that name derived values, and the expression language that ties it all together.

These seven topics are where Terraform stops being a list of resources and starts being a program that computes infrastructure. You will type these constructs into almost every config you write — a variable with a validation block, a common-tags local merged into every resource, a templatefile rendering user-data, a dynamic block generating security-group rules. Get them right and the iteration and module chapters that follow are straightforward.

Topics in This Chapter

Topic 22
Input Variables
A configuration's parameters — the values you change between environments without editing code. Declaring variables, the precedence chain that sets them, and keeping secrets out of the committed defaults.
Inputs
Topic 23
Variable Types and Validation
Primitives, collections, and structural types, plus validation blocks that reject bad input at plan time. How precise types turn a module into a contract with clear errors.
InputsValidation
Topic 24
Outputs
The public return values of a configuration or module — IPs, ARNs, endpoints. Why module internals are reachable only through outputs, and why scripts should consume them as JSON.
Outputs
Topic 25
Local Values
Naming an expression so you compute it once and reuse it. The common-tags pattern, the line between useful DRY and needless indirection, and how locals differ from variables.
Expressions
Topic 26
Expressions and Operators
Arithmetic, comparison, and logical operators, string templates and directives, references and traversal, and heredocs — the connective tissue between resources.
Expressions
Topic 27
Built-in Functions
The fixed library that transforms data — merge, lookup, jsonencode, templatefile, cidrsubnet. Why there are no user-defined functions in core HCL, and the ones you reach for daily.
ExpressionsFunctions
Topic 28
Dynamic Blocks
Generating repeated nested blocks from a collection — multiple ingress rules from a list. The anatomy, the iterator, and the readability cost that makes them easy to overuse.
Expressions