Going to AWS Summit London? 🇬🇧🇬🇧

Meet us there →

Terraform

What are 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 the maintainability of code.

See how you can keep your configuration DRY with Terragrunt on Spacelift.

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 are Terraform Dynamic Blocks?

Dynamic Blocks in Terraform let you repeat configuration blocks inside a resource/provider/provisioner/datasource based on a variable/local/expression you use inside them. 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.

Terraform Dynamic Block components

dynamic blocks are supported inside of resourcedataprovider, and provisioner blocks. A dynamic block consists of the following components:

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. 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.

When working with multi-level nested blocks, the iterators for each block are important. It is recommended to use the optional iterator component to clearly define each level in the configuration, and to remove any ambiguities resulting from attributes with the same name as a parent block.

The listing 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.

How to use the Dynamic Blocks

Terraform provides the dynamic block to create repeatable nested blocks within a resource. A dynamic block is similar to the for expression. Where for creates repeatable top-level resources, like VNets, dynamic creates nested blocks within a top-level resource, like subnets within a VNet. A dynamic block iterates over a child resource and generates a nested block for each element of that resource.

Terraform Dynamic Block examples

Let’s see examples for using Terraform Dynamic Blocks in resource blocks and a data source

Using 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" }
]

Using Terraform Dynamic Block in Data Blocks

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
    }
  }
}

In the above example, 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.

Dynamic Blocks best practices

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 – As you can create multiple instances of resources or resources configurations with Dynamic Blocks, you should be aware of the 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.

Key Points

dynamic block is a great way to apply the DRY principle in Terraform configuration scripts. Implementing a dynamic block where appropriate removes repeated code leading to configurations that are easier to read, maintain, and reuse – just as the DRY principle aims to do.

Note: New versions of Terraform will be 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 will expand on Terraform’s existing concepts and offerings. It is a viable alternative to HashiCorp’s Terraform, being forked from Terraform version 1.5.6. OpenTofu retained all the features and functionalities that had made Terraform popular among developers while also introducing improvements and enhancements. OpenTofu is the future of the Terraform ecosystem, and having a truly open-source project to support all your IaC needs is the main priority.

You can also check out how Spacelift makes it easy to work with Terraform.  It brings with it a GitOps flow, so your infrastructure repository is synced with your Terraform Stacks, and pull requests show you a preview of what they’re planning to change. It also has an extensive selection of policies, which lets you automate compliance checks and build complex multi-stack workflows. You can test drive it for free by creating a trial account.

Manage Terraform Better and Faster

If you are struggling with Terraform automation and management, check out Spacelift. It helps you manage Terraform state, build more complex workflows, and adds several must-have capabilities for end-to-end infrastructure management.

Start free trial
Terraform CLI Commands Cheatsheet

Initialize/ plan/ apply your IaC, manage modules, state, and more.

Share your data and download the cheatsheet