Terraform中partition_count可选字段配置及版本兼容报错求助
解决方案
针对Terraform 0.12/0.15版本无法使用optional()关键字的问题,给你三个实用解决办法:
1. 子模块内用lookup()补默认值
直接在子模块的资源定义里,用lookup()函数处理每个topic对象——如果该对象没有partition_count字段,就用预设的默认值(比如1,根据你的业务需求调整)。这种方式不用改子模块的变量声明,也不用动父模块的传入数据。
示例代码(子模块资源):
resource "kafka_topic" "this" { for_each = { for t in var.topics : t.name => t } name = each.value.name # 无partition_count时用默认值1 partition_count = lookup(each.value, "partition_count", 1) replication_factor = each.value.replication_factor }
2. 父模块预处理topics列表
在调用子模块前,先给所有topic对象补全partition_count的默认值,确保传给子模块的每个元素都包含这个必填字段。
示例代码(父模块调用子模块):
module "kafka_topics" { source = "./modules/kafka-topics" topics = [ # 遍历传入的topics,给缺省的元素补上默认partition_count for t in var.topics : merge(t, { partition_count = lookup(t, "partition_count", 1) }) ] }
这种方式能保留子模块变量的必填约束,不会放松类型检查,适合对类型严谨性要求高的场景。
3. 子模块变量允许字段为null(备选)
Terraform 0.12-0.15没有optional(),但可以通过允许partition_count为null来实现可选,再在资源里处理null的情况。不过这种方式需要确保传入的对象要么有该字段,要么显式设为null,不如前两种灵活。
子模块变量声明修改:
variable "topics" { type = list(object({ name = string partition_count = number # 允许字段为null replication_factor = number })) default = [] }
资源里处理null值:
resource "kafka_topic" "this" { for_each = { for t in var.topics : t.name => t } name = each.value.name partition_count = each.value.partition_count != null ? each.value.partition_count : 1 replication_factor = each.value.replication_factor }
内容的提问来源于stack exchange,提问作者ravvi
相关产品推荐
相关产品推荐

