-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtfws.go
75 lines (63 loc) · 2.12 KB
/
tfws.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package main
import (
"fmt"
"log"
"os/exec"
"strings"
"github.com/AlecAivazis/survey/v2"
)
func main() {
// Execute the Terraform command to get the current workspace
currentCmd := exec.Command("terraform", "workspace", "show")
currentOutput, err := currentCmd.Output()
if err != nil {
log.Fatalf("Failed to execute 'terraform workspace show': %s", err)
}
currentWorkspace := strings.TrimSpace(string(currentOutput))
// Execute the Terraform command to get the list of workspaces
cmd := exec.Command("terraform", "workspace", "list", "-no-color")
output, err := cmd.Output()
if err != nil {
log.Fatalf("Failed to execute 'terraform workspace list'.\nMake sure that you have run 'terraform init'.")
}
// Split the output into individual lines
workspaces := strings.Split(strings.TrimSpace(string(output)), "\n")
// Remove leading/trailing spaces and asterisks, and count the number of workspaces
var validWorkspaces []string
for _, workspace := range workspaces {
workspaceName := strings.TrimSpace(workspace)
workspaceName = strings.ReplaceAll(workspaceName, "*", "")
workspaceName = strings.TrimSpace(workspaceName)
if workspaceName != "" {
validWorkspaces = append(validWorkspaces, workspaceName)
}
}
// Display message if there is only one workspace
if len(validWorkspaces) == 1 {
fmt.Println("There are no workspaces in use in the current project.")
fmt.Println("To create a new one, use 'terraform workspace new'")
return
}
items := make([]string, len(validWorkspaces))
defaultIndex := 0
for i, workspace := range validWorkspaces {
items[i] = workspace
if workspace == currentWorkspace {
defaultIndex = i
}
}
prompt := &survey.Select{
Message: "Select a Terraform workspace:",
Options: items,
Default: items[defaultIndex],
}
var selectedWorkspace string
err = survey.AskOne(prompt, &selectedWorkspace, survey.WithPageSize(10))
if err != nil {
log.Fatalf("Failed to run the prompt: %s", err)
}
cmd = exec.Command("terraform", "workspace", "select", selectedWorkspace)
if err := cmd.Run(); err != nil {
log.Fatalf("Failed to execute 'terraform workspace select': %s", err)
}
}