helper/schema: use reflection to set maps

This commit is contained in:
Mitchell Hashimoto 2014-08-18 15:17:18 -07:00
parent 3800dffdeb
commit dfede5791c
2 changed files with 52 additions and 1 deletions

View File

@ -394,7 +394,19 @@ func (d *ResourceData) setMapValue(
} }
*/ */
vs := value.(map[string]interface{}) v := reflect.ValueOf(value)
if v.Kind() != reflect.Map {
return fmt.Errorf("%s: must be a map", k)
}
if v.Type().Key().Kind() != reflect.String {
return fmt.Errorf("%s: keys must strings", k)
}
vs := make(map[string]interface{})
for _, mk := range v.MapKeys() {
mv := v.MapIndex(mk)
vs[mk.String()] = mv.Interface()
}
for subKey, v := range vs { for subKey, v := range vs {
err := d.set(fmt.Sprintf("%s.%s", k, subKey), nil, elemSchema, v) err := d.set(fmt.Sprintf("%s.%s", k, subKey), nil, elemSchema, v)
if err != nil { if err != nil {

View File

@ -907,6 +907,45 @@ func TestResourceDataSet(t *testing.T) {
}, },
}, },
}, },
// Set a list of maps
{
Schema: map[string]*Schema{
"config_vars": &Schema{
Type: TypeList,
Optional: true,
Computed: true,
Elem: &Schema{
Type: TypeMap,
},
},
},
State: nil,
Diff: nil,
Key: "config_vars",
Value: []interface{}{
map[string]string{
"foo": "bar",
},
map[string]string{
"bar": "baz",
},
},
Err: false,
GetKey: "config_vars",
GetValue: []interface{}{
map[string]interface{}{
"foo": "bar",
},
map[string]interface{}{
"bar": "baz",
},
},
},
} }
for i, tc := range cases { for i, tc := range cases {