From 37cf52fa27e0a48bf23925113e2f73e8482abbc7 Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Thu, 21 Aug 2014 22:19:33 -0700 Subject: [PATCH] helper/schema: if no ID is set then return nil --- helper/schema/resource.go | 2 +- helper/schema/resource_data.go | 7 +++++++ helper/schema/resource_data_test.go | 18 +++++++++++++++++- 3 files changed, 25 insertions(+), 2 deletions(-) diff --git a/helper/schema/resource.go b/helper/schema/resource.go index ff0cea07f..fcf795186 100644 --- a/helper/schema/resource.go +++ b/helper/schema/resource.go @@ -108,7 +108,7 @@ func (r *Resource) Refresh( err = r.Read(data, meta) state := data.State() - if state.ID == "" { + if state != nil && state.ID == "" { state = nil } diff --git a/helper/schema/resource_data.go b/helper/schema/resource_data.go index eb8eaaba3..b81719d18 100644 --- a/helper/schema/resource_data.go +++ b/helper/schema/resource_data.go @@ -141,6 +141,13 @@ func (d *ResourceData) SetDependencies(ds []terraform.ResourceDependency) { func (d *ResourceData) State() *terraform.ResourceState { var result terraform.ResourceState result.ID = d.Id() + + // If we have no ID, then this resource doesn't exist and we just + // return nil. + if result.ID == "" { + return nil + } + result.Attributes = d.stateObject("", d.schema) result.ConnInfo = d.ConnInfo() result.Dependencies = d.Dependencies() diff --git a/helper/schema/resource_data_test.go b/helper/schema/resource_data_test.go index 3fee496c3..82a94da31 100644 --- a/helper/schema/resource_data_test.go +++ b/helper/schema/resource_data_test.go @@ -1524,7 +1524,21 @@ func TestResourceDataState(t *testing.T) { } } + // Set an ID so that the state returned is not nil + idSet := false + if d.Id() == "" { + idSet = true + d.SetId("foo") + } + actual := d.State() + + // If we set an ID, then undo what we did so the comparison works + if actual != nil && idSet { + actual.ID = "" + delete(actual.Attributes, "id") + } + if !reflect.DeepEqual(actual, tc.Result) { t.Fatalf("Bad: %d\n\n%#v", i, actual) } @@ -1533,6 +1547,7 @@ func TestResourceDataState(t *testing.T) { func TestResourceDataSetConnInfo(t *testing.T) { d := &ResourceData{} + d.SetId("foo") d.SetConnInfo(map[string]string{ "foo": "bar", }) @@ -1549,6 +1564,7 @@ func TestResourceDataSetConnInfo(t *testing.T) { func TestResourceDataSetDependencies(t *testing.T) { d := &ResourceData{} + d.SetId("foo") d.SetDependencies([]terraform.ResourceDependency{ terraform.ResourceDependency{ID: "foo"}, }) @@ -1580,7 +1596,7 @@ func TestResourceDataSetId_clear(t *testing.T) { d.SetId("") actual := d.State() - if actual.ID != "" { + if actual != nil { t.Fatalf("bad: %#v", actual) } }