Terraform使用for_each遍历列表创建Servicebus主题报错如何解决
报错的核心原因是Terraform的for_each仅支持map类型或字符串set类型作为入参,你当前定义的local.topics是复杂object结构组成的tuple(列表),无法通过toset()转换为符合要求的入参类型。
你只需要调整local块的输出结构,把原来的列表转换为以主题名称为唯一key的map即可,修改后的配置如下:
调整后的local块代码
locals { topics = { for topic in var.topics : topic.name => merge({ name = "" status = "Active" auto_delete_on_idle = null default_message_ttl = null enable_batched_operations = null enable_express = null enable_partitioning = null max_size = null enable_duplicate_detection = null enable_ordering = null authorization_rules = [] subscriptions = [] duplicate_detection_history_time_window = null }, topic) } }
调整后的maintf资源块代码
resource "azurerm_servicebus_topic" "topic" { for_each = local.topics name = each.value.name resource_group_name = var.resource_group_name namespace_name = azurerm_servicebus_namespace.servicebus.name status = each.value.status auto_delete_on_idle = each.value.auto_delete_on_idle default_message_ttl = each.value.default_message_ttl enable_batched_operations = each.value.enable_batched_operations enable_express = each.value.enable_express enable_partitioning = each.value.enable_partitioning max_size_in_megabytes = each.value.max_size requires_duplicate_detection = each.value.enable_duplicate_detection support_ordering = each.value.enable_ordering duplicate_detection_history_time_window = each.value.duplicate_detection_history_time_window }
这种写法以主题名称作为map的唯一key,既符合for_each的参数要求,后续调整主题配置时,Terraform也能根据key精准识别需要变更的资源,不会因为列表顺序变化触发不必要的重建。如果存在主题名称重复的场景,也可以把map的key替换为索引idx,写法为for idx, topic in var.topics : tostring(idx) => merge(xxx, topic)即可。
内容的提问来源于stack exchange,提问作者prakashrajansakthivel
相关产品推荐
相关产品推荐

