简体   繁体   English

如何在 terraform for_each 中正确循环?

[英]How to loop correctly in terraform for_each?

Objective : Loop through azure subnets via terraform.目标:通过 terraform 遍历 azure 子网。

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.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 https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/network_security_group

You have only a single instance of azurerm_network_security_group.nsg .您只有一个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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM