Practice DRY in Terraform Configurations Using a Dynamic Block
Tags: terraform, devops, iac
Published: 2022-07-15 22:59:19

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](https://spacelift.io/blog/terragrunt-with-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 which 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.

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

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

```terraform
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_:

```terraform
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:

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

##Dynamic Block Components

`dynamic` blocks are supported inside of `resource`, `data`, `provider`, 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. |
|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.

```terraform
  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 which are easier to read, maintain, and reuse - just as the DRY principle aims to do.