Bird
Raised Fist0
Terraformcloud~10 mins

Nested dynamic blocks in Terraform - Commands & Configuration

Choose your learning style10 modes available
Introduction
Sometimes you need to create multiple layers of repeated configuration in Terraform. Nested dynamic blocks let you generate these layers automatically, so you don't have to write repetitive code by hand.
When you want to create multiple nested resources or settings that depend on lists or maps.
When your infrastructure has complex repeating patterns, like multiple security rules inside multiple firewall rules.
When you want to keep your Terraform code clean and avoid copy-pasting similar blocks.
When you need to generate nested blocks dynamically based on variable input.
When you want to manage complex cloud resources with many nested options efficiently.
Config File - main.tf
main.tf
variable "firewalls" {
  type = list(object({
    name  = string
    rules = list(object({
      protocol = string
      ports    = list(number)
    }))
  }))
  default = [
    {
      name = "fw1"
      rules = [
        { protocol = "tcp", ports = [80, 443] },
        { protocol = "udp", ports = [53] }
      ]
    },
    {
      name = "fw2"
      rules = [
        { protocol = "tcp", ports = [22] }
      ]
    }
  ]
}

resource "example_firewall" "firewall" {
  for_each = { for fw in var.firewalls : fw.name => fw }

  name = each.key

  dynamic "rule" {
    for_each = each.value.rules
    content {
      protocol = rule.value.protocol

      dynamic "port" {
        for_each = rule.value.ports
        content {
          number = port.value
        }
      }
    }
  }
}

This Terraform file defines a variable firewalls which is a list of firewall objects. Each firewall has a name and a list of rules. Each rule has a protocol and a list of ports.

The example_firewall resource uses for_each to create one resource per firewall.

Inside the resource, a dynamic "rule" block creates multiple rule blocks based on the rules list.

Inside each rule block, another dynamic "port" block creates multiple port blocks for each port number.

This nested dynamic block structure lets Terraform generate complex nested configurations automatically.

Commands
Initialize Terraform to download providers and prepare the working directory.
Terminal
terraform init
Expected OutputExpected
Initializing the backend... Initializing provider plugins... - Finding latest version of hashicorp/example... - Installing hashicorp/example v1.0.0... - Installed hashicorp/example v1.0.0 (signed by HashiCorp) Terraform has been successfully initialized!
Show the execution plan to see what resources Terraform will create based on the nested dynamic blocks.
Terminal
terraform plan
Expected OutputExpected
An execution plan has been generated and is shown below. Resource actions are indicated with the following symbols: + create Terraform will perform the following actions: # example_firewall.firewall["fw1"] will be created + resource "example_firewall" "firewall" { + name = "fw1" + rule { + protocol = "tcp" + port { + number = 80 } + port { + number = 443 } } + rule { + protocol = "udp" + port { + number = 53 } } } # example_firewall.firewall["fw2"] will be created + resource "example_firewall" "firewall" { + name = "fw2" + rule { + protocol = "tcp" + port { + number = 22 } } } Plan: 2 to add, 0 to change, 0 to destroy.
Apply the planned changes to create the firewall resources with nested rules and ports.
Terminal
terraform apply -auto-approve
Expected OutputExpected
example_firewall.firewall["fw1"]: Creating... example_firewall.firewall["fw2"]: Creating... example_firewall.firewall["fw1"]: Creation complete after 2s [id=fw1] example_firewall.firewall["fw2"]: Creation complete after 1s [id=fw2] Apply complete! Resources: 2 added, 0 changed, 0 destroyed.
→
-auto-approve - Skip interactive approval prompt
Display the current state of the created resources to verify nested dynamic blocks were applied correctly.
Terminal
terraform show
Expected OutputExpected
resource "example_firewall" "firewall" { id = "fw1" name = "fw1" rule { protocol = "tcp" port { number = 80 } port { number = 443 } } rule { protocol = "udp" port { number = 53 } } } resource "example_firewall" "firewall" { id = "fw2" name = "fw2" rule { protocol = "tcp" port { number = 22 } } }
Key Concept

If you remember nothing else from this pattern, remember: nested dynamic blocks let you generate multiple layers of repeated configuration automatically from complex input data.

Common Mistakes
Using a static block instead of dynamic inside another dynamic block
Terraform will not repeat the inner block for each item, so nested lists won't be created properly.
Use a dynamic block inside the outer dynamic block to loop over the nested list.
Not using for_each with a map or list for the outer resource
Terraform cannot create multiple resources from a list without for_each or count, so only one resource is created.
Use for_each with a map or list to create one resource per item.
Referencing the wrong variable inside nested dynamic blocks
Terraform will fail or produce incorrect configuration because the inner dynamic block needs to use the correct nested value.
Use the correct iterator variable names like rule.value and port.value inside nested dynamic blocks.
Summary
Define complex nested input data using variables with lists and objects.
Use for_each on resources to create multiple instances from input data.
Use nested dynamic blocks to generate multiple layers of repeated configuration automatically.

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