Skip to content

Commit

Permalink
statePull: tfjson does not support state subcommand, output string in…
Browse files Browse the repository at this point in the history
…stead
  • Loading branch information
pasternak authored and kmoe committed Apr 26, 2022
1 parent 705ec00 commit 0ef7997
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 18 deletions.
40 changes: 23 additions & 17 deletions tfexec/state_pull.go
@@ -1,10 +1,9 @@
package tfexec

import (
"bytes"
"context"
"os/exec"

tfjson "github.com/hashicorp/terraform-json"
)

type statePullConfig struct {
Expand All @@ -13,37 +12,44 @@ type statePullConfig struct {

var defaultStatePullConfig = statePullConfig{}

func (tf *Terraform) StatePull(ctx context.Context) (*tfjson.State, error) {
type StatePullOption interface {
configureShow(*statePullConfig)
}

func (opt *ReattachOption) configureStatePull(conf *statePullConfig) {
conf.reattachInfo = opt.info
}

func (tf *Terraform) StatePull(ctx context.Context, opts ...StatePullOption) (string, error) {
c := defaultStatePullConfig

for _, o := range opts {
o.configureShow(&c)
}

mergeEnv := map[string]string{}
if c.reattachInfo != nil {
reattachStr, err := c.reattachInfo.marshalString()
if err != nil {
return nil, err
return "", err
}
mergeEnv[reattachEnvVar] = reattachStr
}

cmd := tf.statePullCmd(ctx)

var ret tfjson.State
ret.UseJSONNumber(true)
err := tf.runTerraformCmdJSON(ctx, cmd, &ret)
if err != nil {
return nil, err
}
cmd := tf.statePullCmd(ctx, mergeEnv)

err = ret.Validate()
var ret bytes.Buffer
cmd.Stdout = &ret
err := tf.runTerraformCmd(ctx, cmd)
if err != nil {
return nil, err
return "", err
}

return &ret, nil
return ret.String(), nil
}

func (tf *Terraform) statePullCmd(ctx context.Context) *exec.Cmd {
func (tf *Terraform) statePullCmd(ctx context.Context, mergeEnv map[string]string) *exec.Cmd {
args := []string{"state", "pull"}

return tf.buildTerraformCmd(ctx, nil, args...)
return tf.buildTerraformCmd(ctx, mergeEnv, args...)
}
2 changes: 1 addition & 1 deletion tfexec/state_pull_test.go
Expand Up @@ -18,7 +18,7 @@ func TestStatePull(t *testing.T) {
tf.SetEnv(map[string]string{})

t.Run("tfstate", func(t *testing.T) {
statePullCmd := tf.statePullCmd(context.Background())
statePullCmd := tf.statePullCmd(context.Background(), nil)

assertCmd(t, []string{
"state",
Expand Down

0 comments on commit 0ef7997

Please sign in to comment.