使用 count 和 for_each 一起通过 terraform 创建 AKS 附加节点池

Using count and for_each together to create AKS additional node pool by terraform

下面的 Terraform 片段可以完成 0/1/2 个额外的节点池,

resource "azurerm_kubernetes_cluster_node_pool" "aksnp" {
  lifecycle {
    ignore_changes = [
      node_count
    ]
  }
  count                 = local.additional_node_pool_required == "true" ? 1 : 0
  for_each              = var.additional_node_pools
  kubernetes_cluster_id = azurerm_kubernetes_cluster.aks.id
  name                  = each.value.node_os == "Windows" ? substr(each.key, 0, 6) : substr(each.key, 0, 12)
  node_count            = each.value.node_count
  vm_size               = each.value.vm_size
  availability_zones    = each.value.zones
  max_pods              = each.value.max_pods
  os_disk_size_gb       = each.value.os_disk_size_gb
  os_type               = each.value.node_os
  vnet_subnet_id        = var.vnet_subnet_id
  node_taints           = each.value.taints
  enable_auto_scaling   = each.value.cluster_auto_scaling
  min_count             = each.value.cluster_auto_scaling_min_count
  max_count             = each.value.cluster_auto_scaling_max_count
}

不幸的是,它不起作用。它抛出如下明显的错误,

The Terraform configuration must be valid before initialization so that
Terraform can determine which modules and providers need to be installed.
╷
│ Error: Invalid combination of "count" and "for_each"
│
│   on main.tf line 99, in resource "azurerm_kubernetes_cluster_node_pool" "aksnp":
│   99:   for_each              = var.additional_node_pools
│
│ The "count" and "for_each" meta-arguments are mutually-exclusive, only one should be used to be explicit about the number of resources to be created.

我需要你的一些指导和帮助,因为我很困惑如何使用设置创建节点池?

我需要 for_each,因为我希望为客户提供创建尽可能多的额外节点池的选项。

我还有一个要求,一些业务用户可能不会请求额外的节点池。

我们如何解决这两个问题?

在 Terraform 中没有简单的方法吗?

P. S:如何将父模块 (local_additional_pools_required) 的值设置为 false?因为我希望父模块指示子模块 (AKS) 是否要创建额外的节点池。

您也可以只使用 for_each 创建条件资源:

for_each              = local.additional_node_pool_required == "true" ? var.additional_node_pools : {}