You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Terraform list(object)类型变量设置默认值报语法错误如何解决

报错根本原因

你写的第一个default = {...}代码块被错误包裹在了list()函数的括号范围内,Terraform将其识别为list()的第二个入参,因此触发「缺少参数分隔符」的语法报错。
此外你的变量定义还存在3个隐性错误:

  • 同一个variable块中重复定义了两次default参数,属于语法错误
  • 变量类型为list(object),你给的默认值是单个对象结构,类型不匹配
  • 你定义blackhole为布尔类型,但赋值时写了字符串"false",类型校验不通过

解决方案

根据你的使用场景选择对应写法:

场景1:给整个routes列表设置默认值

如果希望用户不传该变量时,默认使用指定的路由列表,写法如下:

variable "routes" {
  type = list(object({
    destination_cidr_block = string
    blackhole              = bool
  }))
  description = "a list of objects containing the cidr blocks of the dest and whether the cidr is a blackhole or not."
  # 示例:默认是空列表
  default = []
  # 如果需要默认带一条路由,改成:
  # default = [{
  #   destination_cidr_block = ""
  #   blackhole = false
  # }]
}

场景2:给列表内对象的单个字段设置默认值

如果希望用户传入路由对象时可以缺省部分字段,由Terraform自动填充默认值(Terraform 0.14及以上版本支持),可以用optional修饰符:

variable "routes" {
  type = list(object({
    destination_cidr_block = string
    # 标记blackhole为可选字段,用户不传时默认填充false
    blackhole              = optional(bool, false)
  }))
  description = "a list of objects containing the cidr blocks of the dest and whether the cidr is a blackhole or not."
  default = null
}

上述写法下,用户传入routes = [{destination_cidr_block = "10.0.0.0/8"}]时,Terraform会自动补全blackhole = false属性,无需用户显式传入。


内容的提问来源于stack exchange,提问作者yossarian2004

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 00:24:04