github.com/terraform-modules-krish/terratest@v0.29.0/modules/terraform/workspace.go (about) 1 package terraform 2 3 import ( 4 "fmt" 5 "regexp" 6 "strings" 7 8 "github.com/terraform-modules-krish/terratest/modules/testing" 9 ) 10 11 // WorkspaceSelectOrNew runs terraform workspace with the given options and the workspace name 12 // and returns a name of the current workspace. It tries to select a workspace with the given 13 // name, or it creates a new one if it doesn't exist. 14 func WorkspaceSelectOrNew(t testing.TestingT, options *Options, name string) string { 15 out, err := WorkspaceSelectOrNewE(t, options, name) 16 if err != nil { 17 t.Fatal(err) 18 } 19 return out 20 } 21 22 // WorkspaceSelectOrNewE runs terraform workspace with the given options and the workspace name 23 // and returns a name of the current workspace. It tries to select a workspace with the given 24 // name, or it creates a new one if it doesn't exist. 25 func WorkspaceSelectOrNewE(t testing.TestingT, options *Options, name string) (string, error) { 26 out, err := RunTerraformCommandE(t, options, "workspace", "list") 27 if err != nil { 28 return "", err 29 } 30 31 if isExistingWorkspace(out, name) { 32 _, err = RunTerraformCommandE(t, options, "workspace", "select", name) 33 } else { 34 _, err = RunTerraformCommandE(t, options, "workspace", "new", name) 35 } 36 if err != nil { 37 return "", err 38 } 39 40 return RunTerraformCommandE(t, options, "workspace", "show") 41 } 42 43 func isExistingWorkspace(out string, name string) bool { 44 workspaces := strings.Split(out, "\n") 45 for _, ws := range workspaces { 46 if nameMatchesWorkspace(name, ws) { 47 return true 48 } 49 } 50 return false 51 } 52 53 func nameMatchesWorkspace(name string, workspace string) bool { 54 // Regex for matching workspace should match for strings with optional leading asterisk "*" 55 // following optional white spaces following the workspace name. 56 // E.g. for the given name "terratest", following strings will match: 57 // 58 // "* terratest" 59 // " terratest" 60 match, _ := regexp.MatchString(fmt.Sprintf("^\\*?\\s*%s$", name), workspace) 61 return match 62 }