Bitzu

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

Single choice

If a dynamic block has the label "setting" and no iterator argument, what is the name of its loop variable?

  1. each
  2. item
  3. setting
  4. 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.

Select all that apply

Which statements about dynamic blocks are correct?

  1. They can be used inside resource, data, provider and provisioner blocks
  2. The for_each of a dynamic block accepts a collection or structural value
  3. For a set, iterator.key equals iterator.value
  4. They can generate a lifecycle block
  5. 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

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.

Download on the App StoreGet it on Google Play

More Terraform Associate 004 topics in this module