You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将VPC信息与路由表ID组合生成Terraform可用映射对象?

Terraform 生成VPC对等路由配置

现有本地变量

我定义了以下本地变量:

vpc_peering = {
  require_dms = 1
  vpc = [
    {
      id     = "vpc-ai"
      owner  = "a"
      cidr   = "10.25.0.0/16"
      name   = "m-development"
      region = "ap-southeast-2"
    }
  ]
}
route_table_ids = [1, 2]

目标格式

需要将上述变量组合成如下结构的映射,用于后续生成路由资源:

vpc_peering_routes = {
  1-vpc-ai = {
    id             = "vpc-ai"
    owner          = "a"
    cidr           = "10.25.0.0/16"
    name           = "m-development"
    region         = "ap-southeast-2"
    route_table_id = 1
  }
  2-vpc-ai = {
    id             = "vpc-ai"
    owner          = "a"
    cidr           = "10.25.0.0/16"
    name           = "m-development"
    region         = "ap-southeast-2"
    route_table_id = 2
  }
}

应用场景

这个映射将用于aws_route资源中,为每个路由表添加对应VPC的CIDR路由:

resource "aws_route" "vpc_peering_private_routes" {
  for_each = local.vpc_peering_routes
   
  route_table_id            = each.value.route_table_id
  destination_cidr_block    = each.value.cidr
  vpc_peering_connection_id = aws_vpc_peering_connection.vpc_peering.id
}

解决方案

尝试过多种merge和映射方法后,最终通过以下代码实现需求:

route_table_cidr_combination = setproduct(local.route_table_ids, local.vpc_peering.vpc)
vpc_peering_cidr_routes = {
   for item in local.route_table_cidr_combination :  "${item[0]}-${item[1].id}" => merge(item[1], {route_table_id = item[0]})
}

内容的提问来源于stack exchange,提问作者Ryan Clemente

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 10:35:25