Bird
Raised Fist0
Terraformcloud~10 mins

Nested dynamic blocks in Terraform - Step-by-Step Execution

Choose your learning style10 modes available
Process Flow - Nested dynamic blocks
Start Terraform config
↓
Identify outer dynamic block
↓
Iterate over outer collection
↓
For each outer item:
↓
Create outer block instance
↓
Identify inner dynamic block
↓
Iterate over inner collection
↓
Create inner block instances
↓
Complete all iterations
↓
Terraform plan/apply with nested blocks
Terraform processes the outer dynamic block by looping over its collection, then for each item, it processes the inner dynamic block by looping over its inner collection, creating nested blocks accordingly.
Execution Sample
Terraform
resource "aws_security_group" "example" {
  dynamic "ingress" {
    for_each = var.ingress_rules
    content {
      from_port = ingress.value.from
      dynamic "cidr_blocks" {
        for_each = ingress.value.cidr_blocks
        content {
          cidr_block = cidr_blocks.value
        }
      }
    }
  }
}
This Terraform code creates a security group with nested dynamic blocks: an outer 'ingress' block iterating over ingress rules, and an inner 'cidr_blocks' block iterating over CIDR blocks for each ingress.
Process Table
StepOuter Loop IndexOuter ItemInner Loop IndexInner ItemActionResulting Block Created
10{"from": 80, "cidr_blocks": ["10.0.0.0/24", "192.168.1.0/24"]}0"10.0.0.0/24"Create ingress block with from_port=80 and cidr_block=10.0.0.0/24ingress[0] with cidr_blocks[0]
20{"from": 80, "cidr_blocks": ["10.0.0.0/24", "192.168.1.0/24"]}1"192.168.1.0/24"Create ingress block with from_port=80 and cidr_block=192.168.1.0/24ingress[0] with cidr_blocks[1]
31{"from": 443, "cidr_blocks": ["0.0.0.0/0"]}0"0.0.0.0/0"Create ingress block with from_port=443 and cidr_block=0.0.0.0/0ingress[1] with cidr_blocks[0]
42{"from": 22, "cidr_blocks": []}N/AN/ACreate ingress block with from_port=22 but no cidr_blocksingress[2] with no cidr_blocks
5N/AN/AN/AN/AAll outer items processedAll nested dynamic blocks created
💡 Outer loop completed all ingress rules; inner loops completed all cidr_blocks for each ingress.
Status Tracker
VariableStartAfter 1After 2After 3Final
outer_indexN/A001Completed
outer_itemN/A{"from": 80, "cidr_blocks": ["10.0.0.0/24", "192.168.1.0/24"]}{"from": 80, "cidr_blocks": ["10.0.0.0/24", "192.168.1.0/24"]}{"from": 443, "cidr_blocks": ["0.0.0.0/0"]}Completed
inner_indexN/A010N/A
inner_itemN/A"10.0.0.0/24""192.168.1.0/24""0.0.0.0/0"N/A
Key Moments - 3 Insights
Why does the inner dynamic block run multiple times for each outer block?
Because the inner dynamic block loops over a collection inside each outer item, it runs once per inner item for every outer item, as shown in execution_table rows 1 and 2 for outer_index 0.
What happens if the inner collection is empty for an outer item?
No inner blocks are created for that outer item, but the outer block still exists. See execution_table row 4 where ingress[2] has no cidr_blocks.
How does Terraform know which blocks belong nested inside others?
Terraform nests inner dynamic blocks inside the outer block's content, matching the loop structure. Each inner block is created within the current outer block iteration, as shown in the nested block creation in execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the inner_item at Step 3?
A"0.0.0.0/0"
B"192.168.1.0/24"
C"10.0.0.0/24"
DNo inner item at Step 3
💡 Hint
Check the 'Inner Item' column in execution_table row with Step 3.
At which outer_index does the inner dynamic block have zero iterations?
A0
B2
C1
DNone, all have inner iterations
💡 Hint
Look at execution_table row 4 where inner loop is N/A and no cidr_blocks exist.
If the outer collection had one more item with two cidr_blocks, how would the execution_table change?
ANo change, only existing items processed
BAdd one row with outer_index 3 and inner_index N/A
CAdd two more rows with outer_index 3 and inner_index 0 and 1
DAdd one row with outer_index 2 and inner_index 2
💡 Hint
Each outer item loops over its inner collection, so two cidr_blocks mean two inner iterations.
Concept Snapshot
Nested dynamic blocks in Terraform:
- Outer dynamic block loops over a collection.
- Inner dynamic block loops over a nested collection inside each outer item.
- Each inner block is created inside its outer block instance.
- Empty inner collections create no inner blocks but outer block still exists.
- Useful for complex nested resource configurations.
Full Transcript
This visual execution trace shows how Terraform processes nested dynamic blocks. First, it loops over the outer collection, creating an outer block for each item. Then, for each outer item, it loops over the inner collection to create nested inner blocks. Variables track the current outer and inner indices and items. The execution table details each step, showing how blocks are created. Key moments clarify common confusions like why inner blocks run multiple times and what happens with empty inner collections. The quiz tests understanding of inner items at specific steps, empty inner loops, and how adding items affects the execution. The snapshot summarizes the concept for quick recall.

Practice

(1/5)
1.

What is the main purpose of using nested dynamic blocks in Terraform?

easy
A. To write static configuration without loops
B. To create repeated blocks inside other repeated blocks dynamically
C. To define provider settings only
D. To manage Terraform state files

Solution

  1. Step 1: Understand dynamic blocks

    Dynamic blocks allow repeating a block multiple times based on a list or map.
  2. Step 2: Understand nested dynamic blocks

    Nested dynamic blocks repeat blocks inside other repeated blocks, useful for complex nested lists.
  3. Final Answer:

    To create repeated blocks inside other repeated blocks dynamically -> Option B
  4. Quick Check:

    Nested dynamic blocks = repeated blocks inside repeated blocks [OK]
Hint: Think of loops inside loops for nested resources [OK]
Common Mistakes:
  • Confusing dynamic blocks with static blocks
  • Using nested dynamic blocks for simple flat lists
  • Thinking dynamic blocks manage state files
2.

Which of the following is the correct syntax to start a nested dynamic block named subnet inside a dynamic block named network?

dynamic "network" {
  for_each = var.networks
  content {
    name = network.value.name
    // What goes here?
  }
}
easy
A. dynamic "subnet" { for_each = network.value.subnets content { cidr_block = subnet.value } }
B. dynamic subnet { for_each = network.value.subnets content { cidr_block = subnet.value } }
C. dynamic "subnet" for_each = network.value.subnets { content { cidr_block = subnet.value } }
D. dynamic "subnet" { for_each = var.subnets content { cidr_block = subnet.value } }

Solution

  1. Step 1: Identify correct dynamic block syntax

    Dynamic blocks require the keyword dynamic, block name in quotes, then for_each and content blocks.
  2. Step 2: Check nested dynamic block context

    Inside the network dynamic block, use network.value.subnets for for_each and define content with subnet.value.
  3. Final Answer:

    dynamic "subnet" { for_each = network.value.subnets content { cidr_block = subnet.value } } -> Option A
  4. Quick Check:

    Correct syntax uses quotes and nested for_each [OK]
Hint: Remember dynamic block name must be in quotes [OK]
Common Mistakes:
  • Omitting quotes around block name
  • Using wrong variable for for_each
  • Placing for_each outside the braces
3.

Given the following Terraform snippet, what will be the value of resource.aws_vpc.example tags after deployment?

variable "vpcs" {
  default = [
    { name = "vpc1", tags = ["tag1", "tag2"] },
    { name = "vpc2", tags = ["tag3"] }
  ]
}

resource "aws_vpc" "example" {
  for_each = { for v in var.vpcs : v.name => v }
  cidr_block = "10.0.0.0/16"

  dynamic "tags" {
    for_each = each.value.tags
    content {
      key   = tags.value
      value = "true"
    }
  }
}
medium
A. Tags will be empty because tags block is not supported inside aws_vpc
B. {"tags" = ["tag1", "tag2"]} for vpc1 and {"tags" = ["tag3"]} for vpc2
C. No tags will be created because dynamic blocks cannot be nested
D. {"tag1" = "true", "tag2" = "true"} for vpc1 and {"tag3" = "true"} for vpc2

Solution

  1. Step 1: Understand for_each on resource

    Resource creates two VPCs named vpc1 and vpc2 with their respective tags list.
  2. Step 2: Analyze nested dynamic block for tags

    Dynamic block iterates over each.value.tags, creating a tag key with value "true" for each tag string.
  3. Final Answer:

    {"tag1" = "true", "tag2" = "true"} for vpc1 and {"tag3" = "true"} for vpc2 -> Option D
  4. Quick Check:

    Dynamic tags create key-value pairs from list items [OK]
Hint: Dynamic blocks create repeated nested blocks from lists [OK]
Common Mistakes:
  • Assuming tags remain as list instead of key-value map
  • Thinking dynamic blocks cannot be nested
  • Ignoring the for_each on resource
4.

Identify the error in this nested dynamic block snippet:

dynamic "network" {
  for_each = var.networks
  content {
    name = network.value.name
    dynamic "subnet" {
      for_each = var.subnets
      content {
        cidr_block = subnet.value.cidr
      }
    }
  }
}
medium
A. Incorrect use of content block inside dynamic
B. Missing quotes around subnet in dynamic block
C. Using var.subnets instead of network.value.subnets for nested for_each
D. network.value.name is invalid syntax

Solution

  1. Step 1: Check nested for_each source

    The nested dynamic block should iterate over subnets related to the current network, not the entire var.subnets list.
  2. Step 2: Confirm correct variable usage

    Using var.subnets ignores the current network context; it should be network.value.subnets to nest properly.
  3. Final Answer:

    Using var.subnets instead of network.value.subnets for nested for_each -> Option C
  4. Quick Check:

    Nested for_each must use parent block's value [OK]
Hint: Nested loops must use parent block's current item [OK]
Common Mistakes:
  • Using global variables instead of nested context
  • Forgetting quotes around dynamic block names
  • Misplacing content blocks
5.

You have a variable var.services which is a list of maps. Each map has a name and a list of ports. You want to create an aws_security_group resource with nested dynamic blocks to create ingress rules for each port of each service. Which Terraform code snippet correctly implements this?

hard
A.
resource "aws_security_group" "example" {
  for_each = { for s in var.services : s.name => s }
  name = each.key

  dynamic "ingress" {
    for_each = each.value.ports
    content {
      from_port   = ingress.value
      to_port     = ingress.value
      protocol    = "tcp"
      cidr_blocks = ["0.0.0.0/0"]
    }
  }
}
B.
resource "aws_security_group" "example" {
  for_each = var.services
  name = each.value.name

  dynamic ingress {
    for_each = each.value.ports
    content {
      from_port = ingress.value
      to_port = ingress.value
      protocol = "tcp"
      cidr_blocks = ["0.0.0.0/0"]
    }
  }
}
C.
resource "aws_security_group" "example" {
  for_each = { for s in var.services : s.name => s }
  name = each.key

  dynamic "ingress" {
    for_each = each.value.ports
    content {
      from_port = ports.value
      to_port = ports.value
      protocol = "tcp"
      cidr_blocks = ["0.0.0.0/0"]
    }
  }
}
D.
resource "aws_security_group" "example" {
  for_each = { for s in var.services : s.name => s }
  name = each.key

  dynamic "ingress" {
    for_each = each.value.ports
    content {
      from_port = ingress.key
      to_port = ingress.key
      protocol = "tcp"
      cidr_blocks = ["0.0.0.0/0"]
    }
  }
}

Solution

  1. Step 1: Use for_each on resource with map keyed by service name

    This allows referencing each service by name with each.key and each.value.
  2. Step 2: Use nested dynamic block for ingress rules

    Dynamic block named "ingress" iterates over each.value.ports with for_each and uses ingress.value for port numbers.
  3. Final Answer:

    Code snippet in Option A correctly uses nested dynamic blocks with proper variable references -> Option A
  4. Quick Check:

    Nested dynamic blocks need correct for_each and value references [OK]
Hint: Use each.value and ingress.value inside nested dynamic blocks [OK]
Common Mistakes:
  • Omitting quotes around dynamic block name
  • Using wrong variable names like ports.value instead of ingress.value
  • Not using map for resource for_each
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard