Terraform 构建在 AWS VPC 模块之上

问题描述 投票:0回答:1

我使用 AWS VPC 模块 (terraform-aws-modules/vpc/aws) 创建具有公有、私有和内部子网的 VPC。我想在我自己的模块中定义更多子网,以便我可以添加每个环境的子网。我遇到的问题是路由表。我想为每个环境创建 3 个路由表,并重用 aws 模块为我创建的 3 个 NAT(每个可用区 1 个)用于私有子网路由。

如何在 aws_route 资源中设置正确的 nat_gateway_ids 以确保 NAT 和子网可用区匹配?

结构:

全局/网络/vpc/main.tf

module "vpc" {
  source = "terraform-aws-modules/vpc/aws"

  name = ******
  cidr = "10.0.0.0/16"

  azs             = var.azs # 3 AZs in the same region
  private_subnets = local.private_subnet_cidrs # 1 of each per az
  public_subnets  = local.public_subnet_cidrs
  intra_subnets   = local.intra_subnet_cidrs

  enable_ipv6            = false
  enable_nat_gateway     = true # One NAT per zone, not subnet.
  enable_vpn_gateway     = true
  one_nat_gateway_per_az = true

  tags = {
    Terraform = "true"
  }
}

模块/网络/子网/main.tf

Defines 3 subnets (public, private, internal) per AZ

模块/网络/routing_tables/main.tf

Defines the routing tables for use with the 3 subnets above.
Match subnets AZs to a NAT in the same AZ defined by the terraform-aws-modules/vpc/aws module.
amazon-web-services terraform amazon-vpc
1个回答
0
投票

可能有一种方法可以实现您想要的目标,但它可能并不像您想要的那么简单。例如,通过拥有 NAT 网关 ID,您可以使用

aws_nat_gateway
数据源来获取相应网关所在的子网:

data "aws_nat_gateway" "default" {
  for_each = toset(module.vpc.natgw_ids)
  id       = each.value
}

由于此数据源还应返回子网 ID,因此您可以将该值传递给查询子网的数据源:

data "aws_subnet" "natgw_subnet" {
  for_each = data.aws_nat_gateway.default
  id       = each.value.subnet_id
}

在其他属性中,此数据源导出

availability_zone
属性,您可以随后输出该属性,例如:

output "nat_gateway_azs" {
  description = "AZs in which NAT gateways are hosted."
  value       = values(data.aws_subnet.natgw_subnet)[*].availability_zone
}

不确定这是否是正确的答案,但我想你可以利用它。

© www.soinside.com 2019 - 2024. All rights reserved.