【发布时间】:2019-07-04 07:47:25
【问题描述】:
Terraform Schema 能否支持 Elem 的多种 Schema 类型?我要解决的问题是来自我的外部 API 的数据是一个具有多种类型的数组——有些元素是字符串,有些是列表。例如,一个值看起来像:
condition = [
"and",
[
"contains",
["foo","bar","baz"],
"website"
]
然后,我为该属性创建我的架构,使其看起来像这样
"condition": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Schema{
Type: schema.TypeList,
},
},
但是,当我运行测试时,我收到一条消息:
condition.0: should be a list
这是有道理的,因为我的架构定义声明每个Elem 都应该是一个列表。有没有办法为Elem 定义多种类型?
更新:
我已将上面的 condition 字段更改为
"condition_json": {
Type: schema.TypeString,
Required: true,
},
我的.tf 文件现在正在使用jsonencode(),如下所示:
variable "condition_list" {
default = [
["and"],
["contains",["path","payload","source"],"website"],
["contains",["path","headers","from","0","address"],"homer"]
]
}
resource "event_rule" "first" {
condition_json = "${jsonencode(var.condition_list)}"
}
当我为我的事件规则对象构建结构时,Condition 字段正在获取condition_json 的值,如下所示:
Condition: d.Get("condition_json").([]interface{}),
因为我在与 API 接口的库中的 Condition 字段如下所示:
Condition []interface{} `json:"condition,omitempty"`
我的问题是我收到一个错误
interface {} is string, not []interface {}
这条消息很有意义,因为我将架构设置为TypeString,但是在我与 API 接口的结构中,我将Condition 键入为[]interface{}。我的问题是,有没有办法将 d.Get("condition_json") 转换为 []interface{} 而不是断言?
我显然遗漏了一些东西,我不确定是什么。 :)
【问题讨论】:
-
根据文档,答案似乎是:否。这意味着您可能无法将其定义为基元而不是聚合。
-
啊,谢谢你的评论!将如何定义为原始帮助?如果我将它们定义为原语,我仍然会遇到同样的问题。