terraformterraform-provider-awstransit-gateway

Error: Invalid index empty tuple The given key does not identify an element in this collection value


I am trying to create associations and routes in transit gateway route table. Below is the code block.

locals {
  vpc_attachments_without_default_route_table_association = {
    for k, v in var.vpc_attachments : k => v if lookup(v, "transit_gateway_default_route_table_association", true) != true
  }
  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" "this" {
  count = var.create_tgw ? 1 : 0

  transit_gateway_id = aws_ec2_transit_gateway.this[0].id

  tags = merge(
    {
      "Name" = format("%s", var.name)
    },
    var.tags,
    var.tgw_route_table_tags,
  )
}


resource "aws_ec2_transit_gateway_route_table_association" "this" {
  for_each = local.vpc_attachments_without_default_route_table_association

  transit_gateway_attachment_id  = aws_ec2_transit_gateway_vpc_attachment.this[each.key].id
  transit_gateway_route_table_id = aws_ec2_transit_gateway_route_table.this[0].id
}

Error: Error: Invalid index\n\n on ../modules/tgw/main.tf line 118, in resource "aws_ec2_transit_gateway_route_table_association" "this":\n 118: transit_gateway_route_table_id = aws_ec2_transit_gateway_route_table.this[0].id\n |----------------\n | aws_ec2_transit_gateway_route_table.this is empty tuple\n\nThe given key does not identify an element in this collection value.\n\n"


Solution

  • aws_ec2_transit_gateway_route_table_association resource depends on aws_ec2_transit_gateway_route_table in your case. Can you try following code.

    resource "aws_ec2_transit_gateway_route_table_association" "this" {
      for_each = var.create_tgw ? local.vpc_attachments_without_default_route_table_association : {}
    
      transit_gateway_attachment_id  = aws_ec2_transit_gateway_vpc_attachment.this[each.key].id
      transit_gateway_route_table_id = aws_ec2_transit_gateway_route_table.this[0].id
    }