-
Notifications
You must be signed in to change notification settings - Fork 785
/
cluster.go
52 lines (46 loc) · 1.85 KB
/
cluster.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
package cluster
import (
"strings"
"github.com/jenkins-x/jx/pkg/kube"
"github.com/pkg/errors"
)
// Name gets the cluster name from the current context
// Note that this just reads the ClusterName from the local kube config, which can be renamed (but is unlikely to happen)
func Name(kuber kube.Kuber) (string, error) {
config, _, err := kuber.LoadConfig()
if err != nil {
return "", err
}
context := kube.CurrentContext(config)
if context == nil {
return "", errors.New("kube context was nil")
}
// context.Cluster will likely be in the form gke_<accountName>_<region>_<clustername>
// Trim off the crud from the beginning context.Cluster
return SimplifiedClusterName(context.Cluster), nil
}
// ShortName returns a short clusters name. Eg, if ClusterName would return tweetypie-jenkinsx-dev, ShortClusterName
// would return tweetypie. This is needed because GCP has character limits on things like service accounts (6-30 chars)
// and combining a long cluster name and a long vault name exceeds this limit
func ShortName(kuber kube.Kuber) (string, error) {
clusterName, err := Name(kuber)
if err != nil {
return "", errors.Wrap(err, "retrieveing the cluster name")
}
end := len(clusterName) - 1
if end > 16 {
end = 16
}
shortClusterName := clusterName[0:end]
if strings.HasSuffix(shortClusterName, "_") || strings.HasSuffix(shortClusterName, "-") {
shortClusterName = shortClusterName[0 : end-1]
}
return shortClusterName, nil
}
// SimplifiedClusterName get the simplified cluster name from the long-winded context cluster name that gets generated
// GKE cluster names as defined in the kube config are of the form gke_<projectname>_<region>_<clustername>
// This method will return <clustername> in the above
func SimplifiedClusterName(complexClusterName string) string {
split := strings.Split(complexClusterName, "_")
return split[len(split)-1]
}