[Virtual Event] IaCConf 2026: Real stories on how infra teams are keeping pace

Register Now ➡️

Terraform

How to Use Terraform Dynamic Blocks (+ Examples)

Practice DRY in Terraform Configurations Using `dynamic` Blocks

The Don’t Repeat Yourself (DRY) principle of software development states that code should be written once and not repeated. An important goal of the DRY principle is to improve code maintainability.

Some Terraform resources include repeatable nested blocks in their arguments. These nested blocks represent separate resources that are related to the containing resource. For example, Azure VNets contain a subnet block attribute that repeats for each subnet within the VNet. This can lead to repeated configuration blocks in a Terraform script, which violates the DRY principle.

Dynamic blocks are a solution for applying DRY in Terraform configuration scripts.

What we will cover:

  1. What are Terraform dynamic blocks?
  2. Why should you use dynamic blocks in Terraform?
  3. When to use dynamic blocks?
  4. How to use a Terraform dynamic block?
  5. Terraform dynamic block use case examples
  6. What is the difference between a dynamic block and for_each in Terraform?
  7. What is the difference between a dynamic block and for in Terraform?
  8. Best practices for using Terraform dynamic blocks

TL;DR

A Terraform dynamic block lets you generate repeated nested blocks inside a single resource using a loop, instead of writing each one out manually. Use it when the number of nested blocks depends on variable input. However, avoid overusing it, as deep nesting hurts readability.

What are Terraform dynamic blocks?

A Terraform dynamic block is a way to create repeated nested blocks in a resource using a loop, instead of writing each one manually. It is mainly used when the number or structure of nested blocks depends on variable input.

Apart from keeping your configuration DRY, dynamic blocks also help you generate dynamic configurations based on your input, enabling your modules to accommodate several different use cases.

In plain terms, if you need to configure something like multiple security group rules or tags, and each one follows the same structure, but with different values, a dynamic block lets you loop through a list and generate those blocks automatically. It uses a for_each expression and a special content block to define what should be repeated.

Note: This guide covers Terraform, but all examples work identically in OpenTofu. Dynamic blocks are part of the HCL language itself, not Terraform-specific functionality.

Terraform dynamic block components

Terraform dynamic blocks are supported inside of resourcedataprovider, and provisioner blocks. A dynamic block consists of a label, for_each, iterator (optional), and content.

Component Description
label Specifies what kind of nested block to generate. In the above example, the label is “subnet”. A subnet resource will be generated for each element in the var.subnets variable.
for_each The complex value to iterate over. (More on Terraform for each.)
iterator (optional) Sets the name of a temporary variable that represents the current element. If not provided, the name of the variable defaults to the label of the dynamic block. An iterator has two attributes: key and value. The key is the element index. Value is the element value.
content Defines the body of each generated block.

dynamic block can only generate attributes that belong to the resource type being created. It isn’t possible to generate meta-argument blocks like lifecycle. Some resource types have blocks with multiple levels of nesting.

The iterators for each block are important when working with multi-level nested blocks. The optional iterator component should be used to clearly define each level in the configuration and remove any ambiguities resulting from attributes with the same name as a parent block.

The configuration below illustrates a nested block example, with clearly defined iterators for each block.

dynamic "origin_group" {
    for_each = var.load_balancer_origin_groups
    iterator = outer_block
    content {
      name = outer_block.key

      dynamic "origin" {
        for_each = outer_block.value.origins
        iterator = inner_block
        content {
          hostname = inner_block.value.hostname
        }
      }
    }
  }

Why should you use dynamic blocks in Terraform?

Having dynamic blocks in your configuration strengthens your Terraform code’s overall capabilities, making it easy to repeat blocks in your resource. They are a fundamental capability of Terraform, and you should leverage them when you want to repeat blocks inside a resource.

Below are the main benefits of using Terraform dynamic blocks:

  • Flexible and easy to re-use: Dynamic blocks allow you to define a block of code once and reuse it multiple times within your Terraform configuration.
  • Simplified management of complex configurations: Dynamic blocks can significantly simplify the code for resources that require multiple nested blocks with similar structures.
  • Reliability: Dynamic blocks help minimize the risk of misconfigurations by reducing the chances of errors that often occur when copying, pasting, and manually modifying large blocks of repetitive code.

When to use dynamic blocks?

Use dynamic blocks in Terraform when you need to generate multiple nested blocks dynamically based on variable inputs. They are useful when the number of blocks or their attributes depend on data that isn’t known at the time of writing the configuration.

  • Creating multiple security rules – Defining multiple security group rules dynamically within an AWS security group.
  • Attaching multiple disks to a VM – Generating disk configurations dynamically based on a list of disk specifications.
  • Assigning IAM policies – Managing multiple IAM role assignments without manually specifying each one.
  • Provisioning network interfaces – Configuring subnets or network interfaces dynamically based on provided variables.

What is one disadvantage of using dynamic blocks in Terraform?

One significant disadvantage of using dynamic blocks is that they can introduce complexity in debugging and readability. When readability is a priority, as excessive use of dynamic blocks can make code harder to understand.

Because the code is generated dynamically, it can be harder to trace and understand the final configuration. This can make troubleshooting issues more challenging, as it may not be immediately clear how the dynamic generation logic translates into the actual resource definitions. While dynamic blocks offer powerful capabilities, they require careful implementation and thorough documentation to mitigate these potential downsides.

How to use a Terraform dynamic block?

To use a Terraform dynamic block, you define a dynamic keyword inside a resource block, allowing you to generate multiple nested blocks dynamically based on a variable or list. In a dynamic block, you can use the following parameters:

  • for_each (required) –  iterates over the value you are providing
  • content (required) – block containing the body of each block that you are going to create
  • iterator (optional) – temporary variable used as an iterator. If you omit it, the iterator will be the block name
  • labels (optional) – list of strings that define the block labels.

You can have nested dynamic blocks or use dynamic blocks to avoid generating an optional block inside configurations.

Let’s take a look at the following example:

resource "helm_release" "nginx" {
 name       = "my-nginx"
 chart      = "nginx"
 repository = "https://charts.bitnami.com/bitnami"
 version    = "13.2.12"

 set {
   name  = "service.type"
   value = "LoadBalancer"
 }

 set {
   name  = "replicaCount"
   value = "2"
 }

 set {
   name  = "ingress.enabled"
   value = "true"
 }
}

As you can see, a helm_release resource is used to deploy nginx in K8s, and it has three set blocks. This block can be easily repeated and generated dynamically by using a dynamic block. This is how you would rewrite the code using a dynamic block:

locals {
 set = {
   set1 = {
       name  = "service.type"
       value = "LoadBalancer"
   }
   set2 = {
       name  = "replicaCount"
       value = "2"
   }
   set3 = {
       name  = "ingress.enabled"
       value = "true"
   }
 }
}
resource "helm_release" "nginx" {
 name       = "my-nginx"
 chart      = "nginx"
 repository = "https://charts.bitnami.com/bitnami"
 version    = "13.2.12"
 dynamic "set" {
   for_each = local.set
   content {
       name = set.value.name
       value = set.value.value
   }
 }
}

This way, you can easily change a local variable instead of changing your resources. Of course, for this to be really reusable and dynamic, you should use variables for all resource parameters, and the for_each in the dynamic block should also happen on a variable.

Using Terraform dynamic block with count meta argument

In Terraform, you can use a dynamic block inside a resource to iterate over a list or map. However, dynamic blocks do not support the count meta-argument directly. Instead, you can use an iterator with the for_each expression inside a dynamic block.

Terraform dynamic block use case examples

Let’s see examples of using Terraform dynamic blocks in resource blocks and a data source

Example 1: Using a Terraform dynamic block in resource blocks

The following code shows the configuration of an Azure VNet and four subnets. In this example, the subnet blocks are written out explicitly, creating repeated code.

resource "azurerm_virtual_network" "dynamic_block" {
  name                = "vnet-dynamicblock-example-centralus"
  resource_group_name = azurerm_resource_group.dynamic_block.name
  location            = azurerm_resource_group.dynamic_block.location
  address_space       = ["10.10.0.0/16"]

  subnet {
    name           = "snet1"
    address_prefix = "10.10.1.0/24"
  }

  subnet {
    name           = "snet2"
    address_prefix = "10.10.2.0/24"
  }

  subnet {
    name           = "snet3"
    address_prefix = "10.10.3.0/24"
  }

  subnet {
    name           = "snet4"
    address_prefix = "10.10.4.0/24"
  }
}

That same configuration using a dynamic block is shown below. Replacing the four subnet blocks with a dynamic block removes repeated attributes, leading to cleaner code that is easier to maintain.

The iterator is optional, and if you omit it, the iterator itself will become the name of the dynamic block. So if we were to omit the iterator above, in the content block for the name, we would have to use subnet.value.name instead of item.value.name

resource "azurerm_virtual_network" "dynamic_block" {
  name                = "vnet-dynamicblock-example-centralus"
  resource_group_name = azurerm_resource_group.dynamic_block.name
  location            = azurerm_resource_group.dynamic_block.location
  address_space       = ["10.10.0.0/16"]

  dynamic "subnet" {
    for_each = var.subnets
    iterator = item   #optional
    content {
      name           = item.value.name
      address_prefix = item.value.address_prefix
    }
  }
}

Here is the definition of the variable subnets:

variable "subnets" {
  description = "list of values to assign to subnets"
  type = list(object({
    name           = string
    address_prefix = string
  }))
}

The values for the subnets variable are defined in a tfvars file. Sample values are:

subnets = [
  { name = "snet1", address_prefix = "10.10.1.0/24" },
  { name = "snet2", address_prefix = "10.10.2.0/24" },
  { name = "snet3", address_prefix = "10.10.3.0/24" },
  { name = "snet4", address_prefix = "10.10.4.0/24" }
]

Example 2: Using a Terraform dynamic block in data blocks

In the example below, we are using a dynamic block to filter AMIs in a data source based on some of their tags. If we get any matches, all these AMIs will be returned in a list that we can use further in our configuration code.

variable "ami_filters" {
  description = "A list of tag filters for finding AMIs"
  default = [
    {
      name   = "tag:Purpose"
      values = ["WebServer"]
    },
    {
      name   = "tag:Environment"
      values = ["Prod"]
    }
  ]
}

data "aws_ami" "custom_ami" {
  most_recent = true
  owners      = ["self"]

  dynamic "filter" {
    for_each = var.ami_filters
    content {
      name   = filter.value.name
      values = filter.value.values
    }
  }
}

Example 3: Creating an AWS Security Group with Terraform dynamic blocks

There are two ways in which you can define security group rules for AWS using Terraform:

  • By using the security group resource and a dedicated security group rule resource
  • By using only the security group resource (Note: This is the historical way of doing things, and it is not recommended anymore)

In the first case, the code will be similar to this:

resource "aws_security_group" "this" {
 for_each = var.sg_params
 vpc_id   = each.value.vpc_id

 tags = {
   Name = each.key
 }
}

resource "aws_security_group_rule" "this" {
 for_each    = var.sg_rule_params
 type        = each.value.type
 from_port   = each.value.from_port
 to_port     = each.value.to_port
 protocol    = each.value.protocol
 cidr_blocks = each.value.cidr_blocks
 security_group_id = aws_security_group.this[each.value.sg_name].id
}

In the second case, the best way to do it would be to use dynamic blocks within the security group:

resource "aws_security_group" "this" {
 for_each = var.sg_params
 vpc_id   = each.value.vpc_id

 tags = {
   Name = each.key
 }

 dynamic "ingress" {
   for_each = [for rule in each.value.sg_rule_params : rule if rule.type == "ingress"]
   content {
     from_port   = ingress.value.from_port
     to_port     = ingress.value.to_port
     protocol    = ingress.value.protocol
     cidr_blocks = ingress.value.cidr_blocks
   }
 }

 dynamic "egress" {
   for_each = [for rule in each.value.sg_rule_params : rule if rule.type == "egress"]
   content {
     from_port   = egress.value.from_port
     to_port     = egress.value.to_port
     protocol    = egress.value.protocol
     cidr_blocks = egress.value.cidr_blocks
   }
 }
}

In this example, we are using two dynamic blocks, one for the ingress traffic and the other for the egress traffic, and a single variable for everything related to the security groups. Keep in mind that AWS warns us against using only the aws_security_group for adding rules because these rules struggle with managing multiple CIDR blocks.

Example 4: Using Terraform dynamic block with lists

Dynamic blocks don’t care if you are using maps, lists, or sets when you are doing the for_each, so for this example, we will use a map(object) variable for defining our variable, and we will use list(object) to iterate through for our dynamic block.

resource "aws_route_table" "this" {
 for_each = var.route_tables
 vpc_id   = each.value.vpc_id


 dynamic "route" {
   for_each = each.value.routes
   content {
     cidr_block = route.value.cidr_block
     gateway_id = route.value.gateway_id
   }
 }
}

variable "route_tables" {
 type = map(object({
   vpc_id = string
   routes = list(object({
     cidr_block = string
     gateway_id = string
   }))
 }))
  default = {
   route_table_1 = {
     vpc_id = "vpc-0a1b2c3d4e5f6g7h8"
     routes = [
       {
         cidr_block = "0.0.0.0/0"
         gateway_id = "igw-0123456789abcdef0"
       },
       {
         cidr_block = "10.0.0.0/16"
         gateway_id = "local"
       }
     ]
   },
 }
}

As you can see, we are building the route table rules using a list.

Example 5: Using conditional statements inside Terraform dynamic blocks

We’ve already built an example that used a conditional statement in the for_each block when we went through the security group example. In this example, we will use a ternary operator to dynamically choose a variable based on a condition in a dynamic block.

resource "aws_instance" "this" {
 ami           = var.ami
 instance_type = var.instance_type

 dynamic "ebs_block_device" {
   for_each = length(var.ebs_volumes) > 0 ? var.ebs_volumes : [
     {
       device_name = "/dev/sdf"
       volume_size = 8
     }
   ]
   content {
     device_name           = ebs_block_device.value.device_name
     volume_size           = ebs_block_device.value.volume_size
   }
 }
}

In this example, if we have any values inside our var.ebs_volumes, we will use them to dynamically generate the ebs volumes based on them. Otherwise, we will use a predefined device and volume_size.

Example 6: Implementing multilevel nested dynamic blocks

Dynamic blocks can be nested within other dynamic blocks in Terraform, but with limitations. Terraform allows dynamic blocks inside other dynamic blocks when defining complex configurations, such as dynamically generating multiple resources or arguments. However, readability and maintainability can become challenging when overused.

When nesting dynamic blocks:

  • The outer dynamic block iterates over a list or map.
  • The inner dynamic block also iterates over a nested collection within each iteration of the outer block.
  • Terraform processes the outer block first, generating the inner blocks accordingly.

Inside some of the Terraform blocks, you can have other blocks embedded. To keep your configuration dry and to take advantage of building how many blocks you want, you can take advantage of nested dynamic blocks. Let’s see an example:

resource "aws_lb_listener" "example" {
 load_balancer_arn = aws_lb.example.arn
 port              = var.port
 protocol          = var.protocol


 dynamic "default_action" {
   for_each = var.actions
   content {
     type = default_action.value.type


     dynamic "authenticate_cognito" {
       for_each = default_action.value.authenticate_cognito ? [1] : []
       content {
         user_pool_arn       = default_action.value.authenticate_cognito.user_pool_arn
         user_pool_client_id = default_action.value.authenticate_cognito.user_pool_client_id
       }
     }
     dynamic "authenticate_oidc" {
       for_each = default_action.value.authenticate_oidc ? [1] : []
       content {
         authorization_endpoint = default_action.value.authorization_endpoint
         client_id              = default_action.value.client_id
         client_secret          = default_action.value.client_secret
         issuer                 = default_action.value.issuer
         token_endpoint         = default_action.value.token_endpoint
         user_info_endpoint     = default_action.value.user_info_endpoint
       }
     }
   }
 }
}

Based on the default action above, and some conditional values, you can authenticate cognito, oidc, both, or none.

What is the difference between a dynamic block and for_each in Terraform?

This is one of the most common points of confusion, because both dynamic blocks and for_each involve iteration, but they operate at completely different levels of your configuration.

for_each on a resource creates multiple instances of that entire resource. Each instance gets its own state entry, its own lifecycle, and can be managed independently. Use it when you need, say, three separate S3 buckets or five separate security groups.

A dynamic block generates multiple nested blocks inside a single resource. The resource itself is one object in state — only its internal configuration is repeated. Use it when a single resource needs multiple repeated sub-configurations, like multiple ingress rules inside one security group or multiple subnets inside one VNet.

Note that these two choices are independent. You can use for_each on almost any resource and dynamic blocks inside almost any resource. The example below just makes the contrast concrete with two common security group patterns.

Consider an AWS security group. Here’s the same goal solved two different ways:

Using for_each on the resource (creates a separate aws_vpc_security_group_ingress_rule resource per rule):

variable "sg_rules" {
  default = {
    http  = { from_port = 80,  to_port = 80,  protocol = "tcp", cidr = "0.0.0.0/0" }
    https = { from_port = 443, to_port = 443, protocol = "tcp", cidr = "0.0.0.0/0" }
    ssh   = { from_port = 22,  to_port = 22,  protocol = "tcp", cidr = "10.0.0.0/8" }
  }
}

resource "aws_security_group" "this" {
  name   = "example"
  vpc_id = var.vpc_id
}

resource "aws_vpc_security_group_ingress_rule" "this" {
  for_each          = var.sg_rules
  from_port         = each.value.from_port
  to_port           = each.value.to_port
  ip_protocol       = each.value.protocol
  cidr_ipv4         = each.value.cidr
  security_group_id = aws_security_group.this.id
}

This creates three separate resources in state: aws_vpc_security_group_ingress_rule.this["http"], ["https"], and ["ssh"]. Each can be added or removed independently.

Using a dynamic block inside the resource (all rules live inside one aws_security_group):

resource "aws_security_group" "this" {
  name   = "example"
  vpc_id = var.vpc_id

  dynamic "ingress" {
    for_each = var.sg_rules
    content {
      from_port   = ingress.value.from_port
      to_port     = ingress.value.to_port
      protocol    = ingress.value.protocol
      cidr_blocks = [ingress.value.cidr]
    }
  }
}

This creates one resource in state with all three ingress rules embedded inside it. If you add a fourth rule, Terraform shows the security group as modified and adds the new rule in place without recreating it.

What is the difference between a dynamic block and for in Terraform?

In Terraform, dynamic blocks are used to dynamically generate nested content within a resource or module, allowing you to iterate over lists to create repeated configurations. On the other hand, for loops are used in expressions to build lists or maps from existing collections. While dynamic blocks focus on the structure of resources, for loops are primarily used for transforming or filtering data.

Read more: Terraform For Loop – Expression Overview with Examples

Best practices for using Terraform dynamic blocks

Here are some of the best practices around Terraform dynamic blocks you should consider:

  • Don’t overuse dynamic blocks — As mentioned before, you should use dynamic blocks in every block that may be repeated (you may even need to not create a block, and you can also do this with dynamic blocks). However, overusing them and going for deep levels of nesting can hurt your overall understanding of the configuration in the future, and it will be harder to explain to other colleagues.
  • Use a meaningful name for your iterator — If you want to skip using an iterator, that’s totally fine because it will reuse the name of the block, but if you do use it, it should have a meaningful name.
  • Validate your data — Dynamic blocks rely on data to be generated. If you are using a variable, take advantage of the validation block and put different conditions in place. On the other hand, if you are using a local, ensure that you perform data checks through loops and functions.
  • Scalability considerations — Dynamic blocks allow you to create multiple instances of resources or resource configurations, so you should be aware of potential scalability concerns, especially in cloud environments where provisioning many resources can affect performance and cost and even hit service limits.
  • Consistent documentation — Thoroughly document your Terraform code, especially your nested dynamic blocks, to make things easier to understand for your team.

Managing Terraform with Spacelift

Spacelift supports all Terraform FOSS features. Dynami blocks are fully supported, so you can easily use them while orchestrating your Terraform code with Spacelift.

With Spacelift, you get:

  • Plan visibility for dynamically generated resources. Because dynamic blocks generate configuration at plan time rather than at write time, it isn’t always obvious what will actually be created until you run terraform plan. Spacelift surfaces a clear, reviewable plan for every run, so your team can see exactly which nested blocks were generated before anything gets applied.
  • Policy as code to control the kind of resources engineers can create, their parameters, how many approvals you need for a run, the kind of tasks you execute, what happens when a pull request is open, and where to send notifications.
  • Stack dependencies to build multi-infrastructure automation workflows. For example, you can build a workflow that generates your EC2 instances using Terraform and combines it with Ansible to configure them.
  • Self-service infrastructure via Templates and Blueprints, enabling your developers to do what matters: developing application code without sacrificing control.
  • Creature comforts such as contexts (reusable containers for your environment variables, files, and hooks), and the ability to run arbitrary code.
  • Drift detection for dynamically generated resources. If a resource generated by a dynamic block is modified out-of-band (for example, a manually added security rule), Spacelift’s drift detection flags it, giving you confidence that your dynamic configuration remains the source of truth.

Spacelift is the infrastructure orchestration platform built for the AI-accelerated software era, managing the full lifecycle for both traditional infrastructure as code and AI-provisioned infrastructure. To learn more about what you can do with Spacelift, check out this article.

Key points

Terraform dynamic blocks are used within resource or module configurations to generate multiple nested blocks dynamically based on a given set of values. They help avoid redundant code by iterating over a list or map and creating multiple instances of a nested configuration.

If you want to elevate your Terraform management, create a free account for Spacelift today or book a demo with one of our engineers.

Note: New versions of Terraform are placed under the BUSL license, but everything created before version 1.5.x stays open-source. OpenTofu is an open-source version of Terraform that expands on Terraform’s existing concepts and offerings. It is a viable alternative to HashiCorp’s Terraform, being forked from Terraform version 1.5.6. 

Manage Terraform better with Spacelift

To streamline your Terraform workflows, check out Spacelift. It orchestrates the full infrastructure lifecycle across Terraform, OpenTofu, and more, with policy as code, drift detection, and developer self-service built in.

Learn more

Frequently asked questions

  • Do Terraform dynamic blocks work in modules?

    Yes. Dynamic blocks work the same way whether they’re used in root modules or child modules. As long as the module input variables expose the data you want to iterate over (for example, a list or map of objects), you can use dynamic blocks inside that module’s resources to generate nested blocks.

  • When should I use a dynamic block instead of count or for_each?

    Use a dynamic block when you need to repeat nested blocks inside a single resource, such as multiple ingress rules on a security group or multiple subnet blocks. Use count or for_each on the resource itself when you need to repeat entire resources or modules.

  • What’s the difference between a dynamic block and a for expression?

    A for expression creates or transforms data structures (lists, maps, objects). A dynamic block creates or repeats configuration blocks in the plan. In practice, you often use them together: a for expression preprocesses data into a convenient shape, and a dynamic block then turns that data into repeated nested blocks.

  • Are dynamic blocks bad for readability?

    They can be. Dynamic blocks are powerful, but they also make configuration harder to read if:

    • The logic is deeply nested
    • The for_each expression is complex
    • The iterator name is generic (like item) instead of descriptive.

    A good rule of thumb: if someone new to the code can’t understand the resource in ~30 seconds, consider simplifying, adding comments, or moving logic into locals.

  • Do dynamic blocks work with OpenTofu as well as Terraform?

    Yes. Dynamic blocks are a language feature of HCL itself, so they work the same way in OpenTofu as in the corresponding Terraform versions.

Terraform Project Structure
Cheat Sheet

Get the Terraform file & project structure

PDF cheat sheet.

terraform files cheat sheet bottom overlay
Share your data and download the cheat sheet