From ecb98e1c432d32522a98426a7695505ed108f651 Mon Sep 17 00:00:00 2001 From: Alisdair McDiarmid Date: Mon, 25 Oct 2021 15:08:10 -0400 Subject: [PATCH] command/init: Fail if -input=false but required When running `terraform init` against a backend with multiple workspaces, none of which are the currently indicated local workspace, Terraform prompts the user to choose a workspace from the list. In automation, using the `-input=false` argument should disable asking for input, but previously would hang instead. --- internal/command/meta_backend.go | 4 ++++ internal/command/meta_backend_test.go | 23 +++++++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/internal/command/meta_backend.go b/internal/command/meta_backend.go index 2524ccb28..640f3bc34 100644 --- a/internal/command/meta_backend.go +++ b/internal/command/meta_backend.go @@ -241,6 +241,10 @@ func (m *Meta) selectWorkspace(b backend.Backend) error { return m.SetWorkspace(workspaces[0]) } + if !m.input { + return fmt.Errorf("Currently selected workspace %q does not exist", workspace) + } + // Otherwise, ask the user to select a workspace from the list of existing workspaces. v, err := m.UIInput().Input(context.Background(), &terraform.InputOpts{ Id: "select-workspace", diff --git a/internal/command/meta_backend_test.go b/internal/command/meta_backend_test.go index be8fec970..b9d8b9116 100644 --- a/internal/command/meta_backend_test.go +++ b/internal/command/meta_backend_test.go @@ -6,6 +6,7 @@ import ( "path/filepath" "reflect" "sort" + "strings" "testing" "github.com/hashicorp/terraform/internal/addrs" @@ -867,6 +868,28 @@ func TestMetaBackend_initSelectedWorkspaceDoesNotExistAutoSelect(t *testing.T) { } } +// Initializing a backend which supports workspaces and does *not* have +// the currently selected workspace with input=false should fail. +func TestMetaBackend_initSelectedWorkspaceDoesNotExistInputFalse(t *testing.T) { + // Create a temporary working directory that is empty + td := tempDir(t) + testCopyDir(t, testFixturePath("init-backend-selected-workspace-doesnt-exist-multi"), td) + defer os.RemoveAll(td) + defer testChdir(t, td)() + + // Setup the meta + m := testMetaBackend(t, nil) + m.input = false + + // Get the backend + _, diags := m.Backend(&BackendOpts{Init: true}) + + // Should fail immediately + if got, want := diags.ErrWithWarnings().Error(), `Currently selected workspace "bar" does not exist`; !strings.Contains(got, want) { + t.Fatalf("wrong error\ngot: %s\nwant: %s", got, want) + } +} + // Changing a configured backend, copying state func TestMetaBackend_configuredChangeCopy(t *testing.T) { // Create a temporary working directory that is empty