From 669fe827f3ceddde5395a5bc6e84ec3db1c57dc5 Mon Sep 17 00:00:00 2001 From: The Terraform Team <52939924+teamterraform@users.noreply.github.com> Date: Mon, 18 Jul 2022 04:27:37 -0400 Subject: [PATCH] Backport of command: fix panic on show when state file is invalid or unavailable into v1.2 (#31447) * backport of commit b45b2530c2684d929a6671b3d1e64f353c167782 * backport of commit a3482b6c9f4223aa3e4adcf770ac617ef1180050 Co-authored-by: Katy Moe --- internal/command/show.go | 2 +- internal/command/show_test.go | 28 +++++++++++++++++++ .../show-corrupt-statefile/terraform.tfstate | 1 + 3 files changed, 30 insertions(+), 1 deletion(-) create mode 100644 internal/command/testdata/show-corrupt-statefile/terraform.tfstate diff --git a/internal/command/show.go b/internal/command/show.go index 0b16ee735285..123b86536eab 100644 --- a/internal/command/show.go +++ b/internal/command/show.go @@ -151,7 +151,7 @@ func (c *ShowCommand) showFromLatestStateSnapshot() (*statefile.File, tfdiags.Di // Get the latest state snapshot from the backend for the current workspace stateFile, stateErr := getStateFromBackend(b, workspace) if stateErr != nil { - diags = diags.Append(stateErr.Error()) + diags = diags.Append(stateErr) return nil, diags } diff --git a/internal/command/show_test.go b/internal/command/show_test.go index 25acbac2906c..2dd0e5abe6eb 100644 --- a/internal/command/show_test.go +++ b/internal/command/show_test.go @@ -905,6 +905,34 @@ func TestShow_planWithNonDefaultStateLineage(t *testing.T) { } } +func TestShow_corruptStatefile(t *testing.T) { + td := t.TempDir() + inputDir := "testdata/show-corrupt-statefile" + testCopyDir(t, inputDir, td) + defer testChdir(t, td)() + + view, done := testView(t) + c := &ShowCommand{ + Meta: Meta{ + testingOverrides: metaOverridesForProvider(testProvider()), + View: view, + }, + } + + code := c.Run([]string{}) + output := done(t) + + if code != 1 { + t.Fatalf("unexpected exit status %d; want 1\ngot: %s", code, output.Stdout()) + } + + got := output.Stderr() + want := `Unsupported state file format` + if !strings.Contains(got, want) { + t.Errorf("unexpected output\ngot: %s\nwant:\n%s", got, want) + } +} + // showFixtureSchema returns a schema suitable for processing the configuration // in testdata/show. This schema should be assigned to a mock provider // named "test". diff --git a/internal/command/testdata/show-corrupt-statefile/terraform.tfstate b/internal/command/testdata/show-corrupt-statefile/terraform.tfstate new file mode 100644 index 000000000000..9977a2836c1a --- /dev/null +++ b/internal/command/testdata/show-corrupt-statefile/terraform.tfstate @@ -0,0 +1 @@ +invalid