【问题标题】:Enable multiple GCP APIs on multiple Projects with foreach (not count)使用 foreach 在多个项目上启用多个 GCP API(不计入)
【发布时间】:2021-10-20 09:01:05
【问题描述】:

我想在多个项目中启用多个 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_projectsvar.apis_customer_projects 都包含列表。

但是正如这篇优秀的article 中所描述的,count 有一些缺点,我宁愿使用foreach

曾经有一个google_project_services(注意复数形式),但目前似乎已被弃用。

【问题讨论】:

    标签: loops google-cloud-platform foreach terraform terraform-provider-gcp


    【解决方案1】:

    根据我的理解,我认为最好的选择是使用 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

    【讨论】:

      猜你喜欢
      • 2021-07-15
      • 1970-01-01
      • 1970-01-01
      • 2021-09-19
      • 2015-08-01
      • 2019-04-25
      • 2016-07-09
      • 1970-01-01
      • 2022-11-17
      相关资源
      最近更新 更多