diff --git a/terraform/context.go b/terraform/context.go index 659772893..0babb455e 100644 --- a/terraform/context.go +++ b/terraform/context.go @@ -460,6 +460,15 @@ func (c *Context) applyWalkFn() depgraph.WalkFunc { // Force the resource state type to be our type rs.Type = r.State.Type + // Force the "id" attribute to be our ID + if rs.ID != "" { + if rs.Attributes == nil { + rs.Attributes = make(map[string]string) + } + + rs.Attributes["id"] = rs.ID + } + var errs []error for ak, av := range rs.Attributes { // If the value is the unknown variable value, then it is an error. diff --git a/terraform/context_test.go b/terraform/context_test.go index 339d2fc31..c591390d1 100644 --- a/terraform/context_test.go +++ b/terraform/context_test.go @@ -542,6 +542,56 @@ func TestContextApply_hook(t *testing.T) { } } +func TestContextApply_idAttr(t *testing.T) { + c := testConfig(t, "apply-idattr") + p := testProvider("aws") + ctx := testContext(t, &ContextOpts{ + Config: c, + Providers: map[string]ResourceProviderFactory{ + "aws": testProviderFuncFixed(p), + }, + }) + + p.ApplyFn = func(s *ResourceState, d *ResourceDiff) (*ResourceState, error) { + result := s.MergeDiff(d) + result.ID = "foo" + result.Attributes = map[string]string{ + "id": "bar", + } + + return result, nil + } + p.DiffFn = func(*ResourceState, *ResourceConfig) (*ResourceDiff, error) { + return &ResourceDiff{ + Attributes: map[string]*ResourceAttrDiff{ + "num": &ResourceAttrDiff{ + New: "bar", + }, + }, + }, nil + } + + if _, err := ctx.Plan(nil); err != nil { + t.Fatalf("err: %s", err) + } + + state, err := ctx.Apply() + if err != nil { + t.Fatalf("err: %s", err) + } + + rs, ok := state.Resources["aws_instance.foo"] + if !ok { + t.Fatal("not in state") + } + if rs.ID != "foo" { + t.Fatalf("bad: %#v", rs.ID) + } + if rs.Attributes["id"] != "foo" { + t.Fatalf("bad: %#v", rs.Attributes) + } +} + func TestContextApply_output(t *testing.T) { c := testConfig(t, "apply-output") p := testProvider("aws") diff --git a/terraform/state.go b/terraform/state.go index 3348beb55..0d5a171a7 100644 --- a/terraform/state.go +++ b/terraform/state.go @@ -92,6 +92,10 @@ func (s *State) String() string { attrKeys := make([]string, 0, len(rs.Attributes)) for ak, _ := range rs.Attributes { + if ak == "id" { + continue + } + attrKeys = append(attrKeys, ak) } sort.Strings(attrKeys) diff --git a/terraform/test-fixtures/apply-idattr/main.tf b/terraform/test-fixtures/apply-idattr/main.tf new file mode 100644 index 000000000..ca956330c --- /dev/null +++ b/terraform/test-fixtures/apply-idattr/main.tf @@ -0,0 +1,2 @@ +resource "aws_instance" "foo" { +} diff --git a/terraform/test-fixtures/apply-unknown/main.tf b/terraform/test-fixtures/apply-unknown/main.tf index 7eec0bf20..ee1564b7a 100644 --- a/terraform/test-fixtures/apply-unknown/main.tf +++ b/terraform/test-fixtures/apply-unknown/main.tf @@ -1,4 +1,4 @@ resource "aws_instance" "foo" { num = "2" - compute = "id" + compute = "foo" }