我正在尝试通过terraform config文件使用以下模式访问Golang中的一个关键元素:
"vehicles": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 5,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"car": {
Type: schema.TypeList,
Optional: true,
MaxItems: 2,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"make": {
Type: schema.TypeString,
Optional: true,
},
"model": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
},
},
}在配置文件中,
resource "type_test" "type_name" {
vehicles {
car {
make = "Toyota"
model = "Camry"
}
car {
make = "Nissan"
model = "Rogue"
}
}
}我想遍历列表并通过Golang访问车辆地图。
terraform崩溃,代码如下:
vehicles_map, ok = d.getOK("vehicles")
if ok {
vehicleSet := vehicles_d.(*schema.Set)List()
for i, vehicle := range vehicleSet {
mdi, ok = vehicle.(map[string]interface{})
if ok {
log.Printf("%v", mdi["vehicles"].(map[string]interface{})["car"])
}
}崩溃日志:
2019-12-25T21 [DEBUG] plugin.terraform-provider: panic: interface conversion: interface {} is nil, not map[string]interface {} 对于线路"log.Printf("%v", mdi["vehicles"].(map[string]interface{})["car"])"
我想打印和访问配置文件中的每个车辆元素,任何帮助都将不胜感激。
发布于 2019-12-26 17:09:03
d.getOK("vehicles")已经使用"vehicles"键执行了索引,这会产生一个*schema.Set。调用它的Set.List()方法,您将获得一个切片(类型为[]interface{})。迭代它的元素将得到表示用map[string]interface{}类型建模的car的值。因此,在循环中,您只需向此类型键入assert,并且不会再次使用"vehicles"或"car"进行索引。
如下所示:
for i, vehicle := range vehicleSet {
car, ok := vehicle.(map[string]interface{})
if ok {
log.Printf("model: %v, make: %v\n", car["model"], car["make"])
}
}https://stackoverflow.com/questions/59484259
复制相似问题