flatten
Function
flatten
takes a list and replaces any elements that are lists with a
flattened sequence of the list contents.
Examples
If any of the nested lists also contain directly-nested lists, these too are flattened recursively:
Indirectly-nested lists, such as those in maps, are not flattened.
Flattening nested structures for for_each
The
resource for_each
and
dynamic
block
language features both require a collection value that has one element for
each repetition.
Sometimes your input data structure isn't naturally in a suitable shape for
use in a for_each
argument, and flatten
can be a useful helper function
when reducing a nested data structure into a flat one.
For example, consider a module that declares a variable like the following:
The above is a reasonable way to model objects that naturally form a tree, such as top-level networks and their subnets. The repetition for the top-level networks can use this variable directly, because it's already in a form where the resulting instances match one-to-one with map elements:
However, in order to declare all of the subnets with a single resource
block, we must first flatten the structure to produce a collection where each
top-level element represents a single subnet:
The above results in one subnet instance per subnet object, while retaining the associations between the subnets and their containing networks.
Related Functions
setproduct
finds all of the combinations of multiple lists or sets of values, which can also be useful when preparing collections for use withfor_each
constructs.