我试图以terraform的形式创建"aws_route“,迭代另一个服务的vpc_peering的route_tables列表。另一个服务vpc destination_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
}这里,我想在这里列表上进行迭代简单地说,我需要一个嵌套的循环,在for_each中计数。我不能在同一个块中同时使用count和for_each,有什么解决办法吗?或者我能把它分成两个模块吗?
发布于 2022-02-01 16:59:22
我们可以使用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
}发布于 2022-08-09 16:13:03
您还可以使用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
}https://stackoverflow.com/questions/70942206
复制相似问题