gpt4 book ai didi

azure - 如何在 terraform for_each 中正确循环?

转载 作者:行者123 更新时间:2023-12-03 06:55:15 32 4
gpt4 key购买 nike

目标:通过 terraform 循环 azure 子网。

我使用的代码:

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
}
}
}
}

我的根模块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"}
}
}

我面临的问题:

错误:

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

刚刚更新了这篇文章,现在我收到如上所述的错误。我指的是下面的文档

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

最佳答案

您只有 azurerm_network_security_group.nsg单个实例。因此没有什么可以迭代的。要修复您的错误,应该是:

target_resource_id         = azurerm_network_security_group.nsg.id

关于azure - 如何在 terraform for_each 中正确循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73054339/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com