Terraform配置Azure ACI时互斥属性dns_name_label与network_profile_id适配方案
报错原因
你给不符合场景的属性赋值了空字符串"",这在Terraform中属于有效值,相当于你显式声明了两个互斥属性都存在,AzureRM provider的属性互斥校验会直接触发报错,并不会判断值是否为空。
解决方案1:使用
null代替空字符串(最简便) Terraform中null代表“不设置该属性”,provider会认为未配置该字段,即可绕过互斥校验。修改后代码如下:
resource "azurerm_container_group" "this" { name = var.name location = var.location resource_group_name = var.resource_group_name ip_address_type = var.ip_address_type # 不符合条件时返回null,即不配置该属性 dns_name_label = var.ip_address_type == "Public" && length(var.dns_name_label) > 0 ? var.dns_name_label : null os_type = var.os_type restart_policy = var.restart_policy # 不符合条件时返回null,即不配置该属性 network_profile_id = var.ip_address_type == "Private" ? azurerm_network_profile.this[0].id : null }
建议同步给ip_address_type变量增加校验规则,避免传入非法值:
variable "ip_address_type" { type = string description = "IP address type for the container group, allowed values are Public or Private" validation { condition = contains(["Public", "Private"], var.ip_address_type) error_message = "Allowed values for ip_address_type are Public or Private." } }
解决方案2:使用count拆分两个资源实例(适合逻辑差异大的场景)
如果两种网络模式下的资源配置差异很大,也可以用count分别声明公网和私网的容器组实例,保证每个实例只配置对应属性:
# 公网IP场景的容器组 resource "azurerm_container_group" "public" { count = var.ip_address_type == "Public" ? 1 : 0 name = var.name location = var.location resource_group_name = var.resource_group_name ip_address_type = "Public" dns_name_label = length(var.dns_name_label) > 0 ? var.dns_name_label : null os_type = var.os_type restart_policy = var.restart_policy } # 私网IP场景的容器组 resource "azurerm_container_group" "private" { count = var.ip_address_type == "Private" ? 1 : 0 name = var.name location = var.location resource_group_name = var.resource_group_name ip_address_type = "Private" os_type = var.os_type restart_policy = var.restart_policy network_profile_id = azurerm_network_profile.this[0].id } # 对外统一输出容器组属性 output "container_group_id" { value = var.ip_address_type == "Public" ? azurerm_container_group.public[0].id : azurerm_container_group.private[0].id }
内容的提问来源于stack exchange,提问作者Roger Chen
相关产品推荐
相关产品推荐

