From f93c9c23d5e68756ea5cf4613b7fc8fcb5758daa Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Fri, 11 Jul 2014 11:36:44 -0700 Subject: [PATCH] helper/diff: don't delete keys from diff if computed --- helper/diff/resource_builder.go | 24 ++++++++++++++++++++++-- helper/diff/resource_builder_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 2 deletions(-) diff --git a/helper/diff/resource_builder.go b/helper/diff/resource_builder.go index c011db1cf..c388d56a3 100644 --- a/helper/diff/resource_builder.go +++ b/helper/diff/resource_builder.go @@ -33,6 +33,12 @@ type ResourceBuilder struct { // Attrs are the mapping of attributes that can be set from the // configuration, and the affect they have. See the documentation for // AttrType for more info. + // + // Sometimes attributes in here are also computed. For example, an + // "availability_zone" might be optional, but will be chosen for you + // by AWS. In that case, specify it both here and in ComputedAttrs. + // This will make sure that the absense of the configuration won't + // cause a diff by setting it to the empty string. Attrs map[string]AttrType // ComputedAttrs are the attributes that are computed at @@ -98,7 +104,8 @@ func (b *ResourceBuilder) Diff( } } - // Go through our attribues and find the deleted keys + // Find all the keys that are in our attributes right now that + // we also care about. matchingKeys := make(map[string]struct{}) for k, _ := range s.Attributes { // Find only the attributes that match our prefix @@ -106,10 +113,23 @@ func (b *ResourceBuilder) Diff( continue } + // If this key is computed, then we don't ever delete it + comp := false + for _, ck := range b.ComputedAttrs { + if ck == k { + comp = true + break + } + } + if comp { + continue + } + matchingKeys[k] = struct{}{} } - // Delete the keys we saw to find the deleted keys + // Delete the keys we saw in the configuration from the keys + // that are currently set. for _, k := range seenKeys { delete(matchingKeys, k) } diff --git a/helper/diff/resource_builder_test.go b/helper/diff/resource_builder_test.go index 6ad8c3dc3..6a318a716 100644 --- a/helper/diff/resource_builder_test.go +++ b/helper/diff/resource_builder_test.go @@ -7,6 +7,33 @@ import ( "github.com/hashicorp/terraform/terraform" ) +func TestResourceBuilder_replaceComputed(t *testing.T) { + rb := &ResourceBuilder{ + Attrs: map[string]AttrType{ + "foo": AttrTypeCreate, + }, + ComputedAttrs: []string{ + "foo", + }, + } + + state := &terraform.ResourceState{ + ID: "foo", + Attributes: map[string]string{ + "foo": "bar", + }, + } + c := testConfig(t, nil, nil) + + diff, err := rb.Diff(state, c) + if err != nil { + t.Fatalf("err: %s", err) + } + if diff != nil { + t.Fatalf("should be nil: %#v", diff) + } +} + func TestResourceBuilder_complex(t *testing.T) { rb := &ResourceBuilder{ Attrs: map[string]AttrType{