首页 > 解决方案 > Terraform 'for each' 循环遍历作为字符串列表的元素,而不是应用

问题描述

我即将创建一个路由表并将它们关联到子网,所以我(list of strings)已经创建了 3 个子网,但是当我尝试将路由表关联到子网时,它只与第一个关联,而且我当我尝试关联一个NAT也是list of strings.

这是输出:

  + nat_list = [
      + "nat-0980ffedd5471b76d",
      + "nat-053701e207f6e92b2",
      + "nat-0be06d45baf164edc",
    ]

  + subnets  = [
      + "subnet-04c920f8908d7e502",
      + "subnet-0e9e9333180cab627",
      + "subnet-0caae55b544e4b63d",
    ]

这是我的main.tf

resource "aws_route_table" "public" {
   count  = length(local.azs)
   vpc_id = aws_vpc.vpc[0].id
   tags   = var.tags
} <<< Creating without any problems



resource "aws_route" "public_ipv4"  {
   for_each       = { for route in local.public_ipv4 : route.name => route}
   route_table_id = aws_route_table.public.*.id
   
   ...  ...
   
   nat_gateway_id         = ??? lookup(each.value, "nat", "" ) Not working ???
   destination_cidr_block = lookup(each.value, "destination_cidr_block", "" )
   
   ...  ...
}



resource "aws_route_table_association" "public"  {
   count          = length(local.azs)
   subnet_id      = lookup(var.parameters[count.index], "public_subnet", [])
   route_table_id = aws_route_table.public.*.id
}



variable "parameters"                {
   description = "The route table parameters"   
   type        = list(object({
     ... ...
     public_subnet = list(string)
     ... ...
   }))
   default     = []
}

更新:本地变量

locals {
    public_ipv4 = {[
        {
           name = "NAT(s) to MyLogSys ${local.counter + 1 }"
           nat = aws_nat_gateway.translate.*.id 
           destination_cidr_block = "100.0.20.0/20"
        }
    ]}
}

我做了一个研究,但似乎没有类似的问题

标签: amazon-web-servicesterraform

解决方案


基于聊天讨论。

建议更换:

for_each       = { for route in local.public_ipv4 : route.name => route}

for_each       = { for idx, route in local.public_ipv4 : idx => route}

其中 idx 将0,1,2,...根据local.public_ipv4.

为了防止访问列表中元素少于 的元素local.public_ipv4可以使用 element。


推荐阅读