-
Notifications
You must be signed in to change notification settings - Fork 90
/
k3d.go
100 lines (86 loc) · 2.52 KB
/
k3d.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package cluster
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"time"
//lint:ignore ST1001 since Ginkgo and Gomega are DSLs this makes the tests more natural to read
. "github.com/onsi/ginkgo/v2"
//lint:ignore ST1001 since Ginkgo and Gomega are DSLs this makes the tests more natural to read
. "github.com/onsi/gomega"
"github.com/onsi/gomega/gexec"
"github.com/replicatedhq/kots/e2e/util"
)
type K3d struct {
workspace string
kubeconfig string
clusterName string
}
func NewK3d(workspace string) *K3d {
c := &K3d{
workspace: workspace,
}
c.kubeconfig = filepath.Join(c.workspace, ".kubeconfig")
c.clusterName = filepath.Base(c.workspace)
session, err := k3dClusterCreate(c.clusterName)
if err != nil {
c.Teardown()
}
Expect(err).WithOffset(1).Should(Succeed(), "create cluster")
Eventually(session).WithOffset(1).WithTimeout(time.Minute).Should(gexec.Exit(0), "create cluster")
session, err = k3dWriteKubeconfig(c.clusterName, c.kubeconfig)
if err != nil {
c.Teardown()
}
Expect(err).WithOffset(1).Should(Succeed(), "write kubeconfig")
Eventually(session).WithOffset(1).WithTimeout(time.Minute).Should(gexec.Exit(0), "write kubeconfig")
return c
}
func (c *K3d) Teardown() {
if c.clusterName != "" {
session, err := k3dClusterDelete(c.clusterName, c.kubeconfig)
Expect(err).WithOffset(1).Should(Succeed(), "delete cluster")
Eventually(session).WithOffset(1).WithTimeout(time.Minute).Should(gexec.Exit(0), "delete cluster")
}
}
func (c *K3d) PrintDebugInfo() {
GinkgoWriter.Printf("To set kubecontext run:\n export KUBECONFIG=\"$(k3d kubeconfig merge %s)\"\n", c.GetClusterName())
GinkgoWriter.Printf("To delete cluster run:\n k3d cluster delete %s\n", c.GetClusterName())
}
func (c *K3d) GetKubeconfig() string {
return c.kubeconfig
}
func (c *K3d) GetClusterName() string {
return c.clusterName
}
func k3dClusterCreate(clusterName string) (*gexec.Session, error) {
return util.RunCommand(exec.Command(
"k3d",
"cluster",
"create",
"--kubeconfig-update-default=false",
clusterName,
))
}
func k3dClusterDelete(clusterName, kubeconfig string) (*gexec.Session, error) {
cmd := exec.Command(
"k3d",
"cluster",
"delete",
clusterName,
)
cmd.Env = os.Environ()
cmd.Env = append(cmd.Env, fmt.Sprintf("KUBECONFIG=%s", kubeconfig))
return util.RunCommand(cmd)
}
func k3dWriteKubeconfig(clusterName, kubeconfig string) (*gexec.Session, error) {
return util.RunCommand(exec.Command(
"k3d",
"kubeconfig",
"write",
"--overwrite",
fmt.Sprintf("--output=%s", kubeconfig),
clusterName,
))
}