From bc5eecd7f2e9fd261a980e911bb92f3bb8dd985a Mon Sep 17 00:00:00 2001 From: James Bardin Date: Thu, 10 Jan 2019 20:26:54 -0500 Subject: [PATCH] make sure id really gets set in SetId SetId needs to overwrite the newState as well, since the internal calls to DataSource.Id() will override the set attribute. --- helper/schema/resource_data.go | 8 ++++++++ helper/schema/resource_data_test.go | 17 +++++++++++++++-- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/helper/schema/resource_data.go b/helper/schema/resource_data.go index 92d0a73e8..b6969f520 100644 --- a/helper/schema/resource_data.go +++ b/helper/schema/resource_data.go @@ -255,7 +255,15 @@ func (d *ResourceData) SetId(v string) { // once we transition away from the legacy state types, "id" will no longer // be a special field, and will become a normal attribute. + // set the attribute normally d.setWriter.unsafeWriteField("id", v) + + // Make sure the newState is also set, otherwise the old value + // may get precedence. + if d.newState.Attributes == nil { + d.newState.Attributes = map[string]string{} + } + d.newState.Attributes["id"] = v } // SetConnInfo sets the connection info for a resource. diff --git a/helper/schema/resource_data_test.go b/helper/schema/resource_data_test.go index 29d665746..5af0ff8e5 100644 --- a/helper/schema/resource_data_test.go +++ b/helper/schema/resource_data_test.go @@ -3499,14 +3499,27 @@ func TestResourceDataSetMeta_Timeouts(t *testing.T) { } func TestResourceDataSetId(t *testing.T) { - d := &ResourceData{} + d := &ResourceData{ + state: &terraform.InstanceState{ + ID: "test", + Attributes: map[string]string{ + "id": "test", + }, + }, + } d.SetId("foo") actual := d.State() // SetId should set both the ID field as well as the attribute, to aid in // transitioning to the new type system. - if actual.ID != "foo" && actual.Attributes["id"] != "foo" { + if actual.ID != "foo" || actual.Attributes["id"] != "foo" { + t.Fatalf("bad: %#v", actual) + } + + d.SetId("") + actual = d.State() + if actual != nil { t.Fatalf("bad: %#v", actual) } }