Skip to content

Commit

Permalink
Add terraform state pull
Browse files Browse the repository at this point in the history
  • Loading branch information
minamijoyo committed Jul 9, 2020
1 parent 9889247 commit 26d842d
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 0 deletions.
13 changes: 13 additions & 0 deletions tfexec/terraform.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ var tfVersionRe = regexp.MustCompile(`^Terraform v(.+)\s*$`)
type TerraformCLI interface {
// Verison returns a version number of Terraform.
Version(ctx context.Context) (string, error)

// StatePull returns contents of tfstate.
StatePull(ctx context.Context) (string, error)
}

// terraformCLI implements the TerraformCLI interface.
Expand Down Expand Up @@ -59,3 +62,13 @@ func (c *terraformCLI) Version(ctx context.Context) (string, error) {
version := matched[1]
return version, nil
}

// StatePull returns contents of tfstate.
func (c *terraformCLI) StatePull(ctx context.Context) (string, error) {
stdout, err := c.run(ctx, "state", "pull")
if err != nil {
return "", err
}

return stdout, nil
}
62 changes: 62 additions & 0 deletions tfexec/terraform_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,65 @@ func TestTerraformCLIVersion(t *testing.T) {
})
}
}

func TestTerraformCLIStatePull(t *testing.T) {
tfstate := `{
"version": 4,
"terraform_version": "0.12.28",
"serial": 0,
"lineage": "3d2cf549-8051-c117-aaa7-f93cda2674e8",
"outputs": {},
"resources": []
}
`
cases := []struct {
desc string
mockCommands []*mockCommand
want string
ok bool
}{
{
desc: "print tfstate to stdout",
mockCommands: []*mockCommand{
{
args: []string{"terraform", "state", "pull"},
stdout: tfstate,
stderr: "",
exitCode: 0,
},
},
want: tfstate,
ok: true,
},
{
desc: "failed to run terraform state pull",
mockCommands: []*mockCommand{
{
args: []string{"terraform", "state", "pull"},
stdout: "",
stderr: "",
exitCode: 1,
},
},
want: "",
ok: false,
},
}

for _, tc := range cases {
t.Run(tc.desc, func(t *testing.T) {
e := NewMockExecutor(tc.mockCommands)
terraformCLI := NewTerraformCLI(e)
got, err := terraformCLI.StatePull(context.Background())
if tc.ok && err != nil {
t.Fatalf("unexpected err: %s", err)
}
if !tc.ok && err == nil {
t.Fatalf("expected to return an error, but no error, got = %s", got)
}
if got != tc.want {
t.Errorf("got: %s, want: %s", got, tc.want)
}
})
}
}

0 comments on commit 26d842d

Please sign in to comment.