From a22f7e82571927019c58f367b609347385743a82 Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Fri, 19 Aug 2016 11:46:52 -0400 Subject: [PATCH] terraform: State.Add works with multiple resources [GH-7797] --- terraform/state_add.go | 24 ++++++++++++++++++++ terraform/state_add_test.go | 45 +++++++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+) diff --git a/terraform/state_add.go b/terraform/state_add.go index 5aa7957484..f78d293a70 100644 --- a/terraform/state_add.go +++ b/terraform/state_add.go @@ -151,6 +151,28 @@ func stateAddFunc_Resource_Module( } func stateAddFunc_Resource_Resource(s *State, fromAddr, addr *ResourceAddress, raw interface{}) error { + // raw can be either *ResourceState or []*ResourceState. The former means + // we're moving just one resource. The latter means we're moving a count + // of resources. + if list, ok := raw.([]*ResourceState); ok { + // We need at least one item + if len(list) == 0 { + return fmt.Errorf("resource move with no value to: %s", addr) + } + + // Add each with a specific index + for i, rs := range list { + addrCopy := addr.Copy() + addrCopy.Index = i + + if err := s.Add(fromAddr.String(), addrCopy.String(), rs); err != nil { + return err + } + } + + return nil + } + src := raw.(*ResourceState).deepcopy() // Initialize the resource @@ -271,6 +293,8 @@ func detectValueAddLoc(raw interface{}) stateAddLoc { return stateAddModule case *ResourceState: return stateAddResource + case []*ResourceState: + return stateAddResource case *InstanceState: return stateAddInstance default: diff --git a/terraform/state_add_test.go b/terraform/state_add_test.go index 4270ccc032..bb1e619c1b 100644 --- a/terraform/state_add_test.go +++ b/terraform/state_add_test.go @@ -371,6 +371,51 @@ func TestStateAdd(t *testing.T) { }, }, + "ResourceState with count unspecified => Resource Addr (new)": { + false, + "aws_instance.bar", + "aws_instance.foo", + []*ResourceState{ + &ResourceState{ + Type: "test_instance", + Primary: &InstanceState{ + ID: "foo", + }, + }, + + &ResourceState{ + Type: "test_instance", + Primary: &InstanceState{ + ID: "bar", + }, + }, + }, + + &State{}, + &State{ + Modules: []*ModuleState{ + &ModuleState{ + Path: []string{"root"}, + Resources: map[string]*ResourceState{ + "aws_instance.foo.0": &ResourceState{ + Type: "test_instance", + Primary: &InstanceState{ + ID: "foo", + }, + }, + + "aws_instance.foo.1": &ResourceState{ + Type: "test_instance", + Primary: &InstanceState{ + ID: "bar", + }, + }, + }, + }, + }, + }, + }, + "ResourceState => Resource Addr (existing)": { true, "aws_instance.bar",