Search code examples
azureterraformterraform-provider-azure

Terraform for_each on a list


I want to do smth very basic this is my variable file

test = {
  t1 = {
    top = [
        {
            port = "12"
            name = "port12"
        },
        {
            port = "123"
            name = "port123"
        }
    ]
},
  t2 = {
    top = [
        {
            port = "12"
            name = "port12"
        },
        {
            port = "123"
            name = "port123"
        }

    ]
}

}

resource "azurerm_lb_nat_rule" "nat" {
  for_each = var.test 
  resource_group_name = var.rg.name
  loadbalancer_id     = elb.id
  name                = "ELB-XX"
  protocol                       = "Tcp"
  frontend_port                  = each.value.top.port
  backend_port                   = each.value.top.port
  frontend_ip_configuration_name = pip.id
} 

I want :

  • Name like ELB-T1-port12 , ELB-T2-port12 ,ELB-T1-port123 and ELB-T2-port123
  • Retrieve port for frontend_port and backend_port

I can change the variable list


Solution

  • Based on this configuration, you can create the azurerm_lb_nat_rule resources as follows:

    resource "azurerm_lb_nat_rule" "nat" {
      for_each                    = var.test
      resource_group_name         = var.rg.name
      loadbalancer_id             = azurerm_lb.example.id
      protocol                    = "Tcp"
      frontend_ip_configuration   = azurerm_network_interface.example.ip_configuration[0].id
      frontend_port               = "ELB-${each.key}-port${each.value.top[0].port}"
      backend_port                = each.value.top[0].port
      name                        = "ELB-${each.key}-port${each.value.top[0].port}"
    }
    

    You can read more: The for_each Meta-Argument