Terraform NAT网关到设置路由表

时间:2020-10-04 05:32:50

标签: amazon-web-services terraform aws-nat-gateway

我正在尝试在路由表中设置私有的多个NAT网关,但是我对丢失的内容感到困惑。有人可以帮我提供我所缺少的代码吗?

这是我的路线表:

resource "aws_route_table" "private" {
  count                     = length(var.private_subnet_cidr_blocks)
  vpc_id                    = aws_vpc.main_vpc.id

  route {
    cidr_block              = "0.0.0.0/0"
    nat_gateway_id          = aws_nat_gateway.nat-gw[count.index].id
  }

  tags = {
    Name = "private-rtable-${count.index+1}"
  }
}

resource "aws_route_table_association" "private" {
  count                     = length(var.private_subnet_cidr_blocks)
  subnet_id                 = element(aws_subnet.private.*.id, count.index)
  route_table_id            = element(aws_route_table.private.*.id, count.index)
}

这是我的NAT EIP和NAT网关:

resource "aws_eip" "nat-eip" {
  count                     = length(data.aws_availability_zones.available.names)
  vpc                       = true
}

resource "aws_nat_gateway" "nat-gw" {
  count                     = length(data.aws_availability_zones.available.names)
  allocation_id             = element(aws_eip.nat-eip.*.id, count.index)
  subnet_id                 = element(aws_subnet.public.*.id, count.index)

  tags = {
    Name = "NAT-GW-${count.index+1}"
  }
}

我以前想将EACH NAT网关附加到目的地为0.0.0.0/0的路由表,但这无法完成。有没有办法可以使您的NAT网关在体系结构中高度可用,还是应该仅连接一个NAT网关?如果是这种情况,我需要输入什么以使其仅在Terraform中连接一个NAT网关?不胜感激。

更新: 对于对此方案有疑问的任何人,我都会为正在寻找答案的其他人更新代码。

1 个答案:

答案 0 :(得分:1)

aws_route_table.private中,以下内容不正确:

  count                     = var.private_subnet_cidr_blocks

应该是:

  count                     = length(var.private_subnet_cidr_blocks)

您的aws_route_table_association.private代替:

route_table_id            = aws_route_table.private.id

应该是:

route_table_id            = element(aws_route_table.private.*.id, count.index)

原因是您的路由表将与专用子网一样多。