Error: Invalid Index The given key does not identify an element in this collection value Transit gateway routes

Error: Invalid Index The given key does not identify an element in this collection value Transit gateway routes

我正在尝试在中转网关路由 table 中创建路由。下面是代码块。

locals {
  vpc_attachments_with_routes = chunklist(flatten([
    for k, v in var.vpc_attachments : setproduct([{ key = k }], v["tgw_route"]) if length(lookup(v, "tgw_route", {})) > 0
  ]), 2)
  }

resource "aws_ec2_transit_gateway_route_table" "route" {
  count = var.create_tgw ? 1 : 0
  transit_gateway_id = aws_ec2_transit_gateway.this[0].id
}

resource "aws_ec2_transit_gateway_route" "this" {
  count = length(local.vpc_attachments_with_routes)

  destination_cidr_block = local.vpc_attachments_with_routes[count.index][1]["destination_cidr_block"]
  blackhole              = lookup(local.vpc_attachments_with_routes[count.index][1], "blackhole", null)

  transit_gateway_route_table_id = aws_ec2_transit_gateway_route_table.route[count.index].id
  transit_gateway_attachment_id  = tobool(lookup(local.vpc_attachments_with_routes[count.index][1], "blackhole", false)) == false ? aws_ec2_transit_gateway_vpc_attachment.this[local.vpc_attachments_with_routes[count.index][0]["key"]].id : null
   depends_on = [
    aws_ec2_transit_gateway_route_table.route,
  ]
}

错误:

错误:资源“aws_ec2_transit_gateway_route”中 ../modules/tgw/main.tf 第 85 行的 index\n\n 无效 “this”:\n 85: transit_gateway_route_table_id = aws_ec2_transit_gateway_route_table.route[count.index].id\n |----------------\n | aws_ec2_transit_gateway_route_table.route 是包含 1 element\n 的元组 | count.index 是 1\n\nThe 给定键未标识此集合值中的元素。\n\n",

您将只有 0 或 1 个 aws_ec2_transit_gateway_route_table.route,具体取决于 create_tgw 的值。所以应该是:

resource "aws_ec2_transit_gateway_route" "this" {
  count = length(local.vpc_attachments_with_routes)

  destination_cidr_block = local.vpc_attachments_with_routes[count.index][1]["destination_cidr_block"]
  blackhole              = lookup(local.vpc_attachments_with_routes[count.index][1], "blackhole", null)

  transit_gateway_route_table_id = var.create_tgw ? aws_ec2_transit_gateway_route_table.route[0].id : null 

  transit_gateway_attachment_id  = tobool(lookup(local.vpc_attachments_with_routes[count.index][1], "blackhole", false)) == false ? aws_ec2_transit_gateway_vpc_attachment.this[local.vpc_attachments_with_routes[count.index][0]["key"]].id : null
}