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