Search code examples
azureterraformterraform-provider-azureterraform0.12+azure-rm

How to loop correctly in terraform for_each?


Objective: Loop through azure subnets via terraform.

Code That I use:

Main.tf:

resource "azurerm_network_security_group" "nsg" {
  name                = "nsg-vnet-hub-${var.env}-indoundDNS"
  location            = azurerm_resource_group.rg[0].location
  resource_group_name = azurerm_resource_group.rg[0].name
  tags     = {
    environment = "${var.env}"
    costcentre = "12345"
  }
}

    resource "azurerm_monitor_diagnostic_setting" "nsg" {
      for_each                   = var.subnets
      name                       = lower("${each.key}-diag")
      target_resource_id         = azurerm_network_security_group.nsg[each.key].id
      storage_account_id         = azurerm_storage_account.storeacc.id
      log_analytics_workspace_id = azurerm_log_analytics_workspace.logws.id
    
      dynamic "log" {
        for_each = var.nsg_diag_logs
        content {
          category = log.value
          enabled  = true
    
          retention_policy {
            enabled = false
          }
        }
      }
    }

My root module variable.tf :

variable "subnets" {
  type = map(object({
    name    = string
  }))

  default = {
    "s1" = { name = "dns_snet"},
    "s2" = { name = "common_snet"},
    "s3" = { name = "gw_snet"},
    "s4" = { name = "data_snet"}
}
}

Problem I am facing:

Error:

network_security_group_id = azurerm_network_security_group.nsg[each.key].id
│     ├────────────────
│     │ azurerm_network_security_group.nsg is object with 7 attributes
│     │ each.key is "s3"
│ 
│ The given key does not identify an element in this collection value

Just updated this post, now I get error as above. I am referring to below documentation

https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/network_security_group


Solution

  • You have only a single instance of azurerm_network_security_group.nsg. Thus there is nothing to iterate over. To fix your error, it should be:

    target_resource_id         = azurerm_network_security_group.nsg.id