From 7f6a99404dabc02ff6131e9fe923457d34755386 Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Wed, 1 Mar 2017 12:47:36 -0800 Subject: [PATCH] command: fix crash on state pull with empty state When you have no state (no local state or you just switched to a new env) and run `terraform state pull`, it would crash. --- command/state_pull.go | 10 +++++++++- command/state_pull_test.go | 24 ++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/command/state_pull.go b/command/state_pull.go index a51cf5c6a..96c30d9b9 100644 --- a/command/state_pull.go +++ b/command/state_pull.go @@ -43,8 +43,16 @@ func (c *StatePullCommand) Run(args []string) int { return 1 } + s := state.State() + if s == nil { + // Output on "error" so it shows up on stderr + c.Ui.Error("Empty state (no state)") + + return 0 + } + var buf bytes.Buffer - if err := terraform.WriteState(state.State(), &buf); err != nil { + if err := terraform.WriteState(s, &buf); err != nil { c.Ui.Error(fmt.Sprintf("Failed to load state: %s", err)) return 1 } diff --git a/command/state_pull_test.go b/command/state_pull_test.go index 3176a4c54..ac022d726 100644 --- a/command/state_pull_test.go +++ b/command/state_pull_test.go @@ -37,3 +37,27 @@ func TestStatePull(t *testing.T) { t.Fatalf("expected:\n%s\n\nto include: %q", actual, expected) } } + +func TestStatePull_noState(t *testing.T) { + tmp, cwd := testCwd(t) + defer testFixCwd(t, tmp, cwd) + + p := testProvider() + ui := new(cli.MockUi) + c := &StatePullCommand{ + Meta: Meta{ + ContextOpts: testCtxConfig(p), + Ui: ui, + }, + } + + args := []string{} + if code := c.Run(args); code != 0 { + t.Fatalf("bad: %d\n\n%s", code, ui.ErrorWriter.String()) + } + + actual := ui.OutputWriter.String() + if actual != "" { + t.Fatalf("bad: %s", actual) + } +}