From f2368428d3c16ecb2b2dd24e0ea35d8b94d1bc67 Mon Sep 17 00:00:00 2001 From: Paul Hinze Date: Wed, 6 May 2015 10:21:22 -0500 Subject: [PATCH] helper/schema: write "attr.#": "0" for empty maps This fixes some perpetual diffs I saw in Atlas AccTests where an empty map (`map[string]interface{}{}`) was being `d.Set` for "metadata_full". Because the MapFieldWriter was not distinguishing between empty and nil, this trigger the "map delete" logic and no count was written to the state. This caused subsequent plans to improperly report a diff. Here we redefine the map delete functionality to explicitly trigger only on `nil`, so we catch the `.#` field for empty maps. --- helper/schema/field_writer_map.go | 26 ++++++++++++-------------- helper/schema/resource_data_test.go | 4 +++- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/helper/schema/field_writer_map.go b/helper/schema/field_writer_map.go index b9064709f..53e467650 100644 --- a/helper/schema/field_writer_map.go +++ b/helper/schema/field_writer_map.go @@ -141,25 +141,23 @@ func (w *MapFieldWriter) setMap( v := reflect.ValueOf(value) vs := make(map[string]interface{}) - if value != nil { - 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) - } - for _, mk := range v.MapKeys() { - mv := v.MapIndex(mk) - vs[mk.String()] = mv.Interface() - } - } - - if len(vs) == 0 { + if value == nil { // The empty string here means the map is removed. w.result[k] = "" return nil } + 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) + } + for _, mk := range v.MapKeys() { + mv := v.MapIndex(mk) + vs[mk.String()] = mv.Interface() + } + // Remove the pure key since we're setting the full map value delete(w.result, k) diff --git a/helper/schema/resource_data_test.go b/helper/schema/resource_data_test.go index 7d4fdb6a3..3a0c64276 100644 --- a/helper/schema/resource_data_test.go +++ b/helper/schema/resource_data_test.go @@ -2539,7 +2539,9 @@ func TestResourceDataState(t *testing.T) { }, Result: &terraform.InstanceState{ - Attributes: map[string]string{}, + Attributes: map[string]string{ + "tags.#": "0", + }, }, },