【问题标题】:How to for_each over a map inside a map with strings based on workspace如何使用基于工作区的字符串在地图内的地图上进行 for_each
【发布时间】:2022-01-14 16:40:14
【问题描述】:

我有这样的变量:

variable "hosts" {
    type = map(map(string))
    default = {
      workspace1 = {
        hostname1-workspace1-1 = 177.104
        hostname1-workspace1-2 = 177.105
        hostname1-workspace1-3 = 177.106
    }
      workspace2 = {
        hostname1-workspace2-1 = 129.124
        hostname1-workspace2-2 = 129.125
        hostname1-workspace2-3 = 129.126
    }
    }
}

我正在尝试在此映射上进行 for_each,因此我可以为映射中的每个主机创建一个 VM NIC,但仅适用于选择的任何工作空间。 其中 each.key 应该是当前所选工作区的名称,并且 each.value 应该是基于工作区的 IP 地址的最后 2 个八位字节,我尝试过这样的操作:

resource "azurerm_network_interface" "redis_vm_nic" {
    for_each = var.hosts[terraform.workspace]
    name                        = "${each.key}VMNic"
    location                    = "${var.redis_rg_location[terraform.workspace]}"
    resource_group_name         = azurerm_resource_group.infrastructure_redis_rg.name
    ip_configuration {
        name                          = "ipconfig${each.key}"
        subnet_id                     = var.aks_subnet
        private_ip_address_allocation = "Static"
        private_ip_address = "10.99.${each.value}"
    }
    tags =  var.tags_vms
}

但我明白了:

│
│   on main.tf line 59, in resource "azurerm_linux_virtual_machine" "virtual_machine":
│   59:     network_interface_ids = [azurerm_network_interface.redis_vm_nic[each.key].id]
│     ├────────────────
│     │ azurerm_network_interface.redis_vm_nic is object with 3 attributes
│     │ each.key is "workspace1"
│
│ The given key does not identify an element in this collection value.
╵
╷
│ Error: Invalid index
│
│   on main.tf line 59, in resource "azurerm_linux_virtual_machine" "virtual_machine":
│   59:     network_interface_ids = [azurerm_network_interface.redis_vm_nic[each.key].id]
│     ├────────────────
│     │ azurerm_network_interface.redis_vm_nic is object with 3 attributes
│     │ each.key is "workspace2"
│
│ The given key does not identify an element in this collection value.
╵

【问题讨论】:

  • 什么是azurerm_linux_virtual_machine" "虚拟机?

标签: foreach terraform


【解决方案1】:

您的问题肯定不在azurerm_network_interface。您在子地图上正确迭代。我认为问题在于您如何在azurerm_linux_virtual_machine 中执行for_each。从我在错误中看到的情况来看,Linux VM 的for_each 可能是这种格式:

for_each = var.hosts

你最想拥有它在azurerm_network_interface中的样子,所以:

resource "azurerm_linux_virtual_machine" "virtual_machine" {
  for_each = var.hosts[terraform.workspace]
  ...
}

【讨论】:

  • 是的,你是绝对正确的,这就是问题所在。在将工作空间规范添加到需要它的其他资源之后,一切都运行良好。谢谢!
猜你喜欢
  • 2011-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多