Skip to content

Commit

Permalink
Add terraform state mv command
Browse files Browse the repository at this point in the history
  • Loading branch information
minamijoyo committed Jul 22, 2020
1 parent 9922135 commit 4e1b2b6
Show file tree
Hide file tree
Showing 3 changed files with 400 additions and 0 deletions.
4 changes: 4 additions & 0 deletions tfexec/terraform.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,10 @@ type TerraformCLI interface {
// StatePull returns the current tfstate from remote.
StatePull(ctx context.Context, opts ...string) (*State, error)

// StateMv moves resources from source to destination address.
// If a state is given, use it for the input state.
StateMv(ctx context.Context, state *State, source string, destination string, opts ...string) (*State, error)

// StatePush pushs a given State to remote.
StatePush(ctx context.Context, state *State, opts ...string) error
}
Expand Down
56 changes: 56 additions & 0 deletions tfexec/terraform_state_mv.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package tfexec

import (
"context"
"fmt"
"io/ioutil"
"os"
)

// StateMv moves resources from source to destination address.
// If a state is given, use it for the input state.
func (c *terraformCLI) StateMv(ctx context.Context, state *State, source string, destination string, opts ...string) (*State, error) {
args := []string{"state", "mv"}

if state != nil {
if hasPrefixOptions(opts, "-state=") {
return nil, fmt.Errorf("failed to build options. The state argument (!= nil) and the -state= option cannot be set at the same time: state=%v, opts=%v", state, opts)
}
tmpState, err := writeTempFile(state.Bytes())
defer os.Remove(tmpState.Name())
if err != nil {
return nil, err
}
args = append(args, "-state="+tmpState.Name())
}

// disallow -state-out option for writing a state file to a temporary file and load it to memory
if hasPrefixOptions(opts, "-state-out=") {
return nil, fmt.Errorf("failed to build options. The -state-out= option is not allowed. Read a return value: %v", opts)
}

tmpStateOut, err := ioutil.TempFile("", "tfstate")
if err != nil {
return nil, fmt.Errorf("failed to create temporary state out file: %s", err)
}
defer os.Remove(tmpStateOut.Name())

if err := tmpStateOut.Close(); err != nil {
return nil, fmt.Errorf("failed to close temporary state out file: %s", err)
}
args = append(args, "-state-out="+tmpStateOut.Name())

args = append(args, opts...)
args = append(args, source, destination)

_, _, err = c.Run(ctx, args...)
if err != nil {
return nil, err
}

stateOut, err := ioutil.ReadFile(tmpStateOut.Name())
if err != nil {
return nil, err
}
return NewState(stateOut), nil
}

0 comments on commit 4e1b2b6

Please sign in to comment.