Add parsing for workspace already exists error
When calling `terraform workspace new <name>` to create a workspace that already exists, an error is returned.
diff --git a/tfexec/errors.go b/tfexec/errors.go
index 1a14fa1..f401098 100644
--- a/tfexec/errors.go
+++ b/tfexec/errors.go
@@ -21,6 +21,8 @@
noConfigErrRegexp = regexp.MustCompile(`Error: No configuration files`)
workspaceDoesNotExistRegexp = regexp.MustCompile(`Workspace "(.+)" doesn't exist.`)
+
+ workspaceAlreadyExistsRegexp = regexp.MustCompile(`Workspace "(.+)" already exists`)
)
func parseError(err error, stderr string) error {
@@ -51,6 +53,11 @@
if len(submatches) == 2 {
return &ErrNoWorkspace{submatches[1]}
}
+ case workspaceAlreadyExistsRegexp.MatchString(stderr):
+ submatches := workspaceAlreadyExistsRegexp.FindStringSubmatch(stderr)
+ if len(submatches) == 2 {
+ return &ErrWorkspaceExists{submatches[1]}
+ }
}
return errors.New(stderr)
}
@@ -132,3 +139,12 @@
func (err *ErrNoWorkspace) Error() string {
return fmt.Sprintf("workspace %q does not exist", err.Name)
}
+
+// ErrWorkspaceExists is returned when creating a workspace that already exists
+type ErrWorkspaceExists struct {
+ Name string
+}
+
+func (err *ErrWorkspaceExists) Error() string {
+ return fmt.Sprintf("workspace %q already exists", err.Name)
+}
diff --git a/tfexec/internal/e2etest/workspace_test.go b/tfexec/internal/e2etest/workspace_test.go
index d358ffa..d5ff3b6 100644
--- a/tfexec/internal/e2etest/workspace_test.go
+++ b/tfexec/internal/e2etest/workspace_test.go
@@ -52,6 +52,32 @@
})
}
+func TestWorkspace_already_exists(t *testing.T) {
+ runTest(t, "basic", func(t *testing.T, tfv *version.Version, tf *tfexec.Terraform) {
+ const newWorkspace = "existing-workspace"
+ t.Run("create new workspace", func(t *testing.T) {
+ err := tf.WorkspaceNew(context.Background(), newWorkspace)
+ if err != nil {
+ t.Fatalf("got error creating new workspace: %s", err)
+ }
+
+ assertWorkspaceList(t, tf, newWorkspace, newWorkspace)
+ })
+
+ t.Run("create existing workspace", func(t *testing.T) {
+ err := tf.WorkspaceNew(context.Background(), newWorkspace)
+
+ var wsErr *tfexec.ErrWorkspaceExists
+ if !errors.As(err, &wsErr) {
+ t.Fatalf("expected ErrWorkspaceExists, %T returned: %s", err, err)
+ }
+ if wsErr.Name != newWorkspace {
+ t.Fatalf("expected %q, got %q", newWorkspace, wsErr.Name)
+ }
+ })
+ })
+}
+
func TestWorkspace_multiple(t *testing.T) {
runTest(t, "workspaces", func(t *testing.T, tfv *version.Version, tf *tfexec.Terraform) {
assertWorkspaceList(t, tf, "foo", "foo")