Skip to content

Commit 37cf52f

Browse files
committed
helper/schema: if no ID is set then return nil
1 parent 3d37899 commit 37cf52f

3 files changed

Lines changed: 25 additions & 2 deletions

File tree

helper/schema/resource.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ func (r *Resource) Refresh(
108108

109109
err = r.Read(data, meta)
110110
state := data.State()
111-
if state.ID == "" {
111+
if state != nil && state.ID == "" {
112112
state = nil
113113
}
114114

helper/schema/resource_data.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,13 @@ func (d *ResourceData) SetDependencies(ds []terraform.ResourceDependency) {
141141
func (d *ResourceData) State() *terraform.ResourceState {
142142
var result terraform.ResourceState
143143
result.ID = d.Id()
144+
145+
// If we have no ID, then this resource doesn't exist and we just
146+
// return nil.
147+
if result.ID == "" {
148+
return nil
149+
}
150+
144151
result.Attributes = d.stateObject("", d.schema)
145152
result.ConnInfo = d.ConnInfo()
146153
result.Dependencies = d.Dependencies()

helper/schema/resource_data_test.go

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1524,7 +1524,21 @@ func TestResourceDataState(t *testing.T) {
15241524
}
15251525
}
15261526

1527+
// Set an ID so that the state returned is not nil
1528+
idSet := false
1529+
if d.Id() == "" {
1530+
idSet = true
1531+
d.SetId("foo")
1532+
}
1533+
15271534
actual := d.State()
1535+
1536+
// If we set an ID, then undo what we did so the comparison works
1537+
if actual != nil && idSet {
1538+
actual.ID = ""
1539+
delete(actual.Attributes, "id")
1540+
}
1541+
15281542
if !reflect.DeepEqual(actual, tc.Result) {
15291543
t.Fatalf("Bad: %d\n\n%#v", i, actual)
15301544
}
@@ -1533,6 +1547,7 @@ func TestResourceDataState(t *testing.T) {
15331547

15341548
func TestResourceDataSetConnInfo(t *testing.T) {
15351549
d := &ResourceData{}
1550+
d.SetId("foo")
15361551
d.SetConnInfo(map[string]string{
15371552
"foo": "bar",
15381553
})
@@ -1549,6 +1564,7 @@ func TestResourceDataSetConnInfo(t *testing.T) {
15491564

15501565
func TestResourceDataSetDependencies(t *testing.T) {
15511566
d := &ResourceData{}
1567+
d.SetId("foo")
15521568
d.SetDependencies([]terraform.ResourceDependency{
15531569
terraform.ResourceDependency{ID: "foo"},
15541570
})
@@ -1580,7 +1596,7 @@ func TestResourceDataSetId_clear(t *testing.T) {
15801596
d.SetId("")
15811597

15821598
actual := d.State()
1583-
if actual.ID != "" {
1599+
if actual != nil {
15841600
t.Fatalf("bad: %#v", actual)
15851601
}
15861602
}

0 commit comments

Comments
 (0)