For_each 并计算在同一个 terraform AWS 资源中
For_each and count in same terraform AWS resource
我正在尝试在 terraform 中迭代 route_tables 的列表来创建“aws_route”与另一项服务的 vpc_peering。 other service vpc destination_cidr_block是一个list.
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
}
Here,我想遍历 destination_cidr_block 的列表。
简单来说,我需要一个嵌套循环,count inside 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
}
我正在尝试在 terraform 中迭代 route_tables 的列表来创建“aws_route”与另一项服务的 vpc_peering。 other service vpc destination_cidr_block是一个list.
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
}
Here,我想遍历 destination_cidr_block 的列表。 简单来说,我需要一个嵌套循环,count inside 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
}