我想在多个项目上启用多个GCP api。我现在的做法是:
resource "google_project_service" "customer_projects" {
count = length(var.my_projects) * length(var.apis_customer_projects)
project = google_project.customer_projects[var.my_projects[floor(count.index / length(var.apis_customer_projects))]].project_id
service = var.apis_customer_projects[count.index % length(var.apis_customer_projects)]
}
var.my_projects
和var.apis_customer_projects
都包含列表
但是正如这篇优秀的文章所描述的,count
有一些缺点,我更愿意使用foreach
。
曾经有一个google_project_services
(注意复数),但似乎在此期间被弃用。
根据我的理解,我认为最好的选择是使用setproduct()函数循环遍历同一资源中的两个列表变量。
下面是一个来自Terraform文档的例子:
locals {
# setproduct works with sets and lists, but our variables are both maps
# so we'll need to convert them first.
networks = [
for key, network in var.networks : {
key = key
cidr_block = network.cidr_block
}
]
subnets = [
for key, subnet in var.subnets : {
key = key
number = subnet.number
}
]
network_subnets = [
# in pair, element zero is a network and element one is a subnet,
# in all unique combinations.
for pair in setproduct(local.networks, local.subnets) : {
network_key = pair[0].key
subnet_key = pair[1].key
network_id = aws_vpc.example[pair[0].key].id
# The cidr_block is derived from the corresponding network. See the
# cidrsubnet function for more information on how this calculation works.
cidr_block = cidrsubnet(pair[0].cidr_block, 4, pair[1].number)
}
]
}
resource "aws_subnet" "example" {
# local.network_subnets is a list, so we must now project it into a map
# where each key is unique. We'll combine the network and subnet keys to
# produce a single unique key per instance.
for_each = {
for subnet in local.network_subnets : "${subnet.network_key}.${subnet.subnet_key}" => subnet
}
vpc_id = each.value.network_id
availability_zone = each.value.subnet_key
cidr_block = each.value.cidr_block
}
裁判:https://www.terraform.io/docs/language/functions/setproduct.html finding-combinations-for-for_each