在相同地形的AWS资源中查找和计数(_E)



我正在尝试创建">aws_route";在terraform中,使用另一个服务的vpcppeeling在routeTables列表上迭代。另一个服务vpcdestination_cidr_block是一个列表。

variable "route_tables" {
type        = set(string)
description = "Set of route table entries eg : rt-1, rt-2 , rt-3"
}

variable "ext_service_destination_cidr_blocks"{
type = list(string)
description = "list of destination cidr blocks of external service, eg:["10.10.1.1/20", "10.2.10.1/10"]"
}

resource "aws_route" "ext_service_route" {
// iterating over route tables [ rt-1, rt-2 , rt-3 ]
for_each = var.route_tables
route_table_id = each.key
// Iterating over cidr list 
count = var.ext_service_destination_cidr_blocks
destination_cidr_block = var.ext_service_destination_cidr_blocks[count.index]
vpc_peering_connection_id = var.ext_service_peering_connection_id
}

在这里,我想迭代destination_cidr_block的列表。简单地说,我需要一个嵌套循环,在for_each内部计数。我不能在同一个块中同时使用count和for_each,有什么解决方法吗?或者有没有办法把它分成两个模块?

我们可以使用setproduct来计算这两个集合的笛卡尔乘积,并在此基础上创建map。此map可用于对其执行for_each

resource "aws_route" "ext_service_route" {
for_each                  = { for i, pair in tolist(setproduct(var.route_tables, var.ext_service_destination_cidr_blocks)) : "route-${i}" => { "name" : pair[0], "cidr" : pair[1] } }
route_table_id            = each.value.name
destination_cidr_block    = each.value.cidr
vpc_peering_connection_id = var.ext_service_peering_connection_id
}

您还可以使用mod操作同时迭代两个列表(例如,当您使用的是还不支持for_each的旧TF版本时(:

resource "aws_route" "ext_service_route" {
count                     = length(var.ext_service_destination_cidr_blocks) * length(var.route_tables)
route_table_id            = element(var.route_tables, count.index + 1 % length(var.route_tables))
destination_cidr_block    = element(var.ext_service_destination_cidr_blocks, count.index + 1 % length(var.ext_service_destination_cidr_blocks))
vpc_peering_connection_id = var.ext_service_peering_connection_id
}

相关内容

  • 没有找到相关文章

最新更新