Terraform Associate 004 ยท Dynamic configuration
Dynamic blocks: generating repeated nested blocks
dynamic block syntax, for_each and content, iterator, when to use and when not to (4e).
Key points
- A dynamic block builds repeatable nested blocks (such as ingress rules) from a collection.
- Its label is the nested block type, for_each supplies the collection, and content defines the body of each generated block.
- The loop variable is named after the label unless you set iterator; it exposes .key and .value.
- Use them sparingly, because literal nested blocks are easier to read.
Source: https://developer.hashicorp.com/terraform/language/expressions/dynamic-blocks
Practice questions
If a dynamic block has the label "setting" and no iterator argument, what is the name of its loop variable?
- each
- item
- setting
- dynamic
Show answer
Answer: C. setting
The iterator defaults to the label of the dynamic block, so the loop variable is setting. Use iterator only to choose a different name.
Which statements about dynamic blocks are correct?
- They can be used inside resource, data, provider and provisioner blocks
- The for_each of a dynamic block accepts a collection or structural value
- For a set, iterator.key equals iterator.value
- They can generate a lifecycle block
- Every nested block must be written as a dynamic block
Show answer
Answer: A. They can be used inside resource, data, provider and provisioner blocks, B. The for_each of a dynamic block accepts a collection or structural value, C. For a set, iterator.key equals iterator.value
Dynamic blocks work inside resource, data, provider and provisioner blocks, accept any collection in for_each, and for a set the key equals the value. They cannot generate meta-argument blocks such as lifecycle.
True or false: a dynamic block can generate the lifecycle block of a resource.
Show answer
Answer: False
False. Meta-argument blocks such as lifecycle and provisioner are processed before expressions are evaluated, so they cannot be generated dynamically.
Practice 8 questions on this topic in Bitzu
Short lessons, instant explanations and spaced review of what you get wrong. Free on iOS and Android.
