首页 > 解决方案 > 使用 for_each 在 terraform 函数中使用列表/元组

问题描述

我有以下来自 terraform locals 的输出。

  [
    [
      "rt1",
      "rg1",
      "10.0.0.0.1/26",
    ],
    [
      "rt1",
      "rg1",
      "10.0.0.32/24",
     ],
     [
      "rt2",
      "rg2",
      "10.0.0.0.1/26",
     ],
     [
      "rt2",
      "rg2",
      "10.0.0.32/24",
     ],
     [
      "rt3",
      "rg3",
      "10.0.0.0.1/26",
     ],
     [
      "rt3",
      "rg3",
      "10.0.0.32/24",
     ],
   ]

下面是函数。由于输出值为 6 个集合/元组 .. 它应该循环 6 次并替换路由表、资源组和子网 cidr 中的 rt、rg 和 ip。我可以通过 count 获得输出 .. 但我想用 for_each 做到这一点

resource "azurerm_route" "route" {
 count     = length(local.flattened)
 name                = "test"
 resource_group_name = ((local.flattened[count.index])[1])
 route_table_name    = ((local.flattened[count.index])[0])
 address_prefix      = ((local.flattened[count.index])[2])
 next_hop_type       = "VirtualAppliance"
 next_hop_in_ip_address = "10.220.54.16"            
 }

标签: terraform

解决方案


我认为以下应该有效:

resource "azurerm_route" "route" {
   for_each            = {for i,v in local.flattened: i=>v}
   name                = "test"
   resource_group_name = each.value[0]
   route_table_name    = each.value[1]
   address_prefix      = each.value[2]
   next_hop_type       = "VirtualAppliance"
   next_hop_in_ip_address = "10.220.54.16"            
 }

推荐阅读