Terraform object identification when created via for_each

64 views Asked by At

I have a resource to create subnets like this in azurerm with client_name =["client1","client2"]:

    resource "azurerm_subnet" "subnets" {
      for_each             = var.subnet_map_large
      resource_group_name  = var.resource_group_name
      virtual_network_name = var.virtual_network_name
      name                 = "${var.client_name}-${each.key}"
      address_prefixes     = [format("%s.%s", "${var.address_prefix}", each.value["subnet_postfix"])]
    }

This creates the subnets just fine. When I then want to get the id for one of the created subnets like this:

    gateway_ip_configuration {
        name      = "gateway-ip-config"
        subnet_id = azurerm_subnet.subnets["${var.client_name}-AppGatewaySubnet"].id
      }

The error is:

    subnet_id = azurerm_subnet.subnets["${var.client_name}-AppGatewaySubnet"].id
    │     ├────────────────
    │     │ azurerm_subnet.subnets is object with 8 attributes

which puzzles me since a subnet looks like below (result of terraform state show) and has more than 8 attributes. This aside from the fact that I don't know how to address that specific one since I'm very new to Terraform:

    module.client_network["client3"].azurerm_subnet.subnets["API"]:
    resource "azurerm_subnet" "subnets" {
        address_prefixes                               = [
            "10.3.64.0/18",
        ]
        enforce_private_link_endpoint_network_policies = false
        enforce_private_link_service_network_policies  = false
        id                                             = "/subscriptions/747c7dd9-3d75-4dab-abce-c12b580afd12/resourceGroups/RG-AG-4/providers/Microsoft.Network/virtualNetworks/app-network/subnets/client3-API"
        name                                           = "client3-API"
        private_endpoint_network_policies_enabled      = true
        private_link_service_network_policies_enabled  = true
        resource_group_name                            = "RG-AG-4"
        service_endpoint_policy_ids                    = []
        service_endpoints                              = []
        virtual_network_name                           = "app-network"
    }

1

There are 1 answers

0
Wolfgang On

I don't think I posted enough background for anyone to help. Once I thought more about it, I realized that the module, which creates the subnet resources for each client with a "for_each" loop, the module is called once for each client. This means that at the moment when I need the subnet_id from the list of subnets, only one client is actually "active" for a subnet resource "azurerm_subnet.subnets"

As a result, I tried the following:

  gateway_ip_configuration {
    name      = "gateway-ip-config"
    subnet_id = azurerm_subnet.subnets["AppGatewaySubnet"].id
  }

and it worked! Thanks for reading and pondering about it.