我试图用所有可能的参数为AKS编写代码,然后在变量中指定映射。问题是,我不想每次都在变量中指定所有可选参数,我想知道是否有可能在变量中跳过它们。这是我的例子:
main.tf
resource "azurerm_kubernetes_cluster" "this" {
for_each = var.AKS_Config
name = each.value.AKS_Name
location = each.value.AKS_Location
resource_group_name = each.value.AKS_ResourceGroupName
dns_prefix = each.value.dns_prefix
#dns_prefix_private_cluster = # dns_prefix or dns_prefix_private_cluster must be specified
kubernetes_version = each.value.kubernetes_version
automatic_channel_upgrade = each.value.automatic_channel_upgrade
api_server_authorized_ip_ranges = each.value.api_server_authorized_ip_ranges
dynamic "identity" {
for_each = each.value.identity
content {
type = identity.value.type
user_assigned_identity_id = can(identity.value.user_assigned_identity_id) == true ? identity.value.user_assigned_identity_id : {}
}
}
}
variables.tf
variable "AKS_Config" {
default = {
"AKS_1" = {
AKS_Name = "AKSTest001"
AKS_Location = "West Europe"
AKS_ResourceGroupName = "SDSADAS"
dns_prefix = "AKSTESTPREFIX"
default_node_pool_name = "test-name"
node_count = 1
vm_sku = "Standard_D2_v2"
kubernetes_version = "1.21.7"
automatic_channel_upgrade = "stable"
api_server_authorized_ip_ranges = ["16.0.0.0/16"]
identity = {
type = "SystemAssigned"
}
default_node_pool = {
name = "nodetest01"
node_count = 3
vm_size = "Standard_D2_v2"
availability_zones = ["1", "2", "3"]
auto_scaling_enabled = true
enable_host_encryption = false
enable_node_public_ip = true
fips_enabled = true
kubelet_disk_type = "OS"
max_pods = 2
}
}
}
}
正如您所看到的,AKS有很多可选参数,但我不想在每次部署时都将其中的每一个指定为"null"。有实现这一目标的选择吗?某种功能"如果密钥不存在,跳过它">
谢谢
编辑:
你觉得这个";变通办法";?
dynamic "identity" {
for_each = can(each.value.identity) == true ? each.value.identity : {}
content {
type = each.value.identity.type
user_assigned_identity_id = can(each.value.identity.user_assigned_identity_id) == true ? each.value.identity.user_assigned_identity_id : null
}
}
使用can
是有效的,或者至少地形验证不会带来任何问题,我不需要在地图中指定可选参数,但我不知道在的情况下是否应该避免这种情况
通常有两个选项可以处理这个问题:
- 将
default
映射拆分为不同的可用值,并为每个变量分配一个默认值 - 使用merge((地形函数可以覆盖您声明要在
for_each
中使用的default
映射中的特定值