Advanced collection transformations
Build a deployment inventory
Advanced collection functions help transform input data into predictable configuration. Suppose two services must each run in two environments. Rather than copying four declarations, produce four records with stable keys. The following complete local configuration requires no external provider. The provisional Terraform 1.14.8 baseline is retained; examples are reasoned predictions, not executed results.
locals { pairs = setproduct(["catalog", "search"], ["dev", "test"]) deployments = { for p in local.pairs : "${p[0]}-${p[1]}" => { service = p[0] stage = p[1] } }}output "deployment_keys" { value = keys(local.deployments)}Expected keys: catalog-dev, catalog-test, search-dev, search-test. setproduct creates every combination of its input collections; all-list inputs preserve list order, otherwise the result is a set. An empty input gives an empty result. The number of pairs grows multiplicatively: bound the size before using it for resource creation. The key separator is safe only for this fixed inventory; for arbitrary names use an unambiguous encoding such as jsonencode of the pair or validate permitted characters.
Relate parallel lists and reverse associations
When importing tabular data, zipmap associates corresponding keys and values. The lists must have equal length; repeated keys keep the last value, which can hide duplicate input. matchkeys selects values by matching a corresponding key against a search set. Its input lists must align and selected values retain their original ordering. transpose reverses a mapping from strings to lists of strings.
zipmap(["catalog", "search"], [8080, 8081])matchkeys(["catalog", "search", "billing"], ["dev", "test", "dev"], ["dev"])transpose({ catalog = ["dev", "test"], search = ["test"] })These independent console expressions predict a mapping catalog=8080 and search=8081; a list [catalog, billing]; and an inverse mapping dev=[catalog], test=[catalog, search]. Prefer records with explicit fields when possible: sorting just one of two parallel lists silently corrupts associations.
Partition work and enforce cardinality
Use chunklist to divide an ordered list into batches; the last batch may be shorter. Choose a positive integer batch size. A batch is data, not a scheduling or concurrency guarantee. Use one when an optional collection must contain at most one element.
chunklist(["a", "b", "c", "d", "e"], 2)one([])one(["catalog"])# Intentionally invalid: one(["catalog", "search"])Predicted chunks are [[a,b],[c,d],[e]]. one returns null for an empty list, set or tuple, the element for a singleton, and raises an error for more than one. This catches accidental duplicates instead of hiding them with an index.
Normalize labels without hiding invalid input
Pattern matching is useful for parsing established naming conventions. regex returns a string without captures, a sequence for unnamed captures or a map for named captures. Do not mix capture styles. regexall collects matches; use its length to detect absence. replace can perform literal replacement or use a slash-delimited regular expression.
regex("^svc-([0-9]+)$", "svc-42")regexall("[0-9]+", "rack7-slot12")replace("Catalog API", " ", "-")# Intentionally invalid: regex("^[0-9]+$", "dev")Predictions: ["42"], ["7","12"], and "Catalog-API". The invalid expression raises a no-match error. Terraform patterns follow RE2 syntax, not arbitrary PCRE; escape backslashes for the enclosing HCL string. A transformed label may collide with another label, so validate uniqueness after normalization.
Allocate network ranges deliberately
Use cidrsubnets for sequential aligned allocations from a parent prefix. Each argument adds bits to the original prefix length. cidrnetmask returns the IPv4 dotted decimal mask, not an IPv6 mask.
cidrsubnets("192.0.2.0/24", 2, 3, 3)cidrnetmask("192.0.2.0/26")The expected ranges are 192.0.2.0/26, 192.0.2.64/27 and 192.0.2.96/27. The mask is 255.255.255.192. The example uses a documentation network, not a deployment. Appending a range can preserve existing allocations if space remains, but changing earlier sizes can shift later ranges. Verify containment, overlap and ownership before applying real changes.
Practice and review
Use the worksheet to derive stable keys, check alignment and identify cardinality errors. Function calls can propagate unknown inputs; a known output shape does not guarantee every member is known. Do not use an unknown or sensitive result as for_each keys. See the accompanying function-reference notes for signatures and limitations.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Advanced collection transformations — knowledge check
Review advanced function behavior and data boundaries.
What happens if one input to setproduct is empty?
What happens to duplicate zipmap keys?
What does one return for an empty list?
Which expression checks for a match without a no-match regex error?
Why avoid changing early cidrsubnets allocations?