terraform dynamic block - ghdrako/doc_snipets GitHub Wiki

Terraform dynamic blocks are used to create repeatable nested blocks inside an argument. These dynamic blocks represent separate objects that are related or embedded with the containing object. Dynamic blocks are a lot like the for expression except dynamic blocks iterate over complex values.

  1. Collection
  2. Iterator
  3. Content
#Syntax
dynamic "my_dynamic_block" {
  for_each = list | map | set
  iterator = iterator_name
  content {
    key = iterator_name.value
  }  
}
locals {
  subnets = [
    {
      name           = "snet01"
      address_prefix = "192.168.1.0/24"
    },
 
    {
      name           = "snet02"
      address_prefix = "192.168.2.0/24"
    }
  ]
}
resource "azurerm_virtual_network" "vnet" {
  name                = "vnet-westus2"
  resource_group_name = azurerm_resource_group.rg.name
  location            = azurerm_resource_group.rg.location
  address_space       = ["192.168.0.0/16"]
 
  dynamic "subnet" {
    for_each = local.subnets
 
    content {
      name           = subnet.value.name
      address_prefix = subnet.value.address_prefix
    }
  }
}