Skip to content

NimTechnology

Trình bày các công nghệ CLOUD một cách dễ hiểu.

  • Kubernetes & Container
    • Docker
    • Kubernetes
      • Ingress
      • Pod
    • Helm Chart
    • OAuth2 Proxy
    • Isito-EnvoyFilter
    • Apache Kafka
      • Kafka
      • Kafka Connect
      • Lenses
    • Vault
    • Longhorn – Storage
    • VictoriaMetrics
    • MetalLB
    • Kong Gateway
  • CI/CD
    • ArgoCD
    • ArgoWorkflows
    • Argo Events
    • Spinnaker
    • Jenkins
    • Harbor
    • TeamCity
    • Git
      • Bitbucket
  • Coding
    • DevSecOps
    • Terraform
      • GCP – Google Cloud
      • AWS – Amazon Web Service
      • Azure Cloud
    • Golang
    • Laravel
    • Python
    • Jquery & JavaScript
    • Selenium
  • Log, Monitor & Tracing
    • DataDog
    • Prometheus
    • Grafana
    • ELK
      • Kibana
      • Logstash
  • BareMetal
    • NextCloud
  • Toggle search form

[Terraform] DRY in Terraform Configurations With Dynamic Blocks

Posted on April 21, 2023April 21, 2023 By nim No Comments on [Terraform] DRY in Terraform Configurations With Dynamic Blocks

Refer to: https://spacelift.io/blog/terraform-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.

Contents

Toggle
  • How to Use the Dynamic Blocks
    • Example
  • Dynamic Block Components
  • Key Points

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.

Example

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.

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

💡 You might also like:

  • 5 Ways to Manage Terraform at Scale
  • 12 Best Practices for Using Terraform
  • How to Automate Terraform Deployments

Dynamic Block Components

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

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

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

Key Points

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

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.

Terraform

Post navigation

Previous Post: [Argo-Workflows] Lesson23: Setup logging and artifact repository
Next Post: [VScode] Details: libsecret-1.so.0: cannot open shared object file: No such file or director

More Related Articles

[Terraform] Manage Secrets in Terraform (2023) Terraform
[AWS] Create EKS Cluster and EKS Node Groups in Public and Private Subnets AWS - Amazon Web Service
[Terraform] Lesson 7: Cloud BigQuery with Terraform GCP - Google Cloud
[Terraform] Lesson 6: Google Cloud Function with Terraform GCP - Google Cloud
[Terraform] Lesson 8: Cloud PubSub with Terraform GCP - Google Cloud
[Terraform] Let’s look into For Function in terraform Terraform

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Tham Gia Group DevOps nhé!
Để Nim có nhiều động lực ra nhiều bài viết.
Để nhận được những thông báo mới nhất.

Recent Posts

  • [Laravel] Laravel Helpful June 26, 2025
  • [VScode] Hướng dẫn điều chỉnh font cho terminal June 20, 2025
  • [WordPress] Hướng dấn gửi mail trên WordPress thông qua gmail. June 15, 2025
  • [Bitbucket] Git Clone/Pull/Push with Bitbucket through API Token. June 12, 2025
  • [Teamcity] How to transfer the value from pipeline A to pipeline B June 9, 2025

Archives

  • June 2025
  • May 2025
  • April 2025
  • March 2025
  • February 2025
  • January 2025
  • December 2024
  • November 2024
  • October 2024
  • September 2024
  • August 2024
  • July 2024
  • June 2024
  • May 2024
  • April 2024
  • March 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • September 2023
  • August 2023
  • July 2023
  • June 2023
  • May 2023
  • April 2023
  • March 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Categories

  • BareMetal
    • NextCloud
  • CI/CD
    • Argo Events
    • ArgoCD
    • ArgoWorkflows
    • Git
      • Bitbucket
    • Harbor
    • Jenkins
    • Spinnaker
    • TeamCity
  • Coding
    • DevSecOps
    • Golang
    • Jquery & JavaScript
    • Laravel
    • NextJS 14 & ReactJS & Type Script
    • Python
    • Selenium
    • Terraform
      • AWS – Amazon Web Service
      • Azure Cloud
      • GCP – Google Cloud
  • Kubernetes & Container
    • Apache Kafka
      • Kafka
      • Kafka Connect
      • Lenses
    • Docker
    • Helm Chart
    • Isito-EnvoyFilter
    • Kong Gateway
    • Kubernetes
      • Ingress
      • Pod
    • Longhorn – Storage
    • MetalLB
    • OAuth2 Proxy
    • Vault
    • VictoriaMetrics
  • Log, Monitor & Tracing
    • DataDog
    • ELK
      • Kibana
      • Logstash
    • Fluent
    • Grafana
    • Prometheus
  • Uncategorized
  • Admin

Copyright © 2025 NimTechnology.