github.com/olli-ai/jx/v2@v2.0.400-0.20210921045218-14731b4dd448/pkg/kube/cluster/cluster.go (about) 1 package cluster 2 3 import ( 4 "strings" 5 6 "k8s.io/client-go/rest" 7 8 "github.com/olli-ai/jx/v2/pkg/kube/naming" 9 "github.com/pkg/errors" 10 "k8s.io/client-go/tools/clientcmd/api" 11 12 "github.com/olli-ai/jx/v2/pkg/kube" 13 ) 14 15 // Name gets the cluster name from the current context 16 // Note that this just reads the ClusterName from the local kube config, which can be renamed (but is unlikely to happen) 17 func Name(kuber kube.Kuber) (string, error) { 18 context, err := Context(kuber) 19 if err != nil { 20 return "", err 21 } 22 if context == nil { 23 return "", errors.New("kube context was nil") 24 } 25 // context.Cluster will likely be in the form gke_<accountName>_<region>_<clustername> 26 // Trim off the crud from the beginning context.Cluster 27 return SimplifiedClusterName(context.Cluster), nil 28 } 29 30 // Context returns the current kube context 31 func Context(kuber kube.Kuber) (*api.Context, error) { 32 config, _, err := kuber.LoadConfig() 33 if err != nil { 34 return nil, err 35 } 36 if config == nil { 37 return nil, nil 38 } 39 return kube.CurrentContext(config), nil 40 } 41 42 // ShortName returns a short clusters name. Eg, if ClusterName would return tweetypie-jenkinsx-dev, ShortClusterName 43 // would return tweetypie. This is needed because GCP has character limits on things like service accounts (6-30 chars) 44 // and combining a long cluster name and a long vault name exceeds this limit 45 func ShortName(kuber kube.Kuber) (string, error) { 46 clusterName, err := Name(kuber) 47 if err != nil { 48 return "", errors.Wrap(err, "retrieving the cluster name") 49 } 50 return naming.ToValidNameTruncated(clusterName, 16), nil 51 } 52 53 // SimplifiedClusterName get the simplified cluster name from the long-winded context cluster name that gets generated 54 // GKE cluster names as defined in the kube config are of the form gke_<projectname>_<region>_<clustername> 55 // This method will return <clustername> in the above 56 func SimplifiedClusterName(complexClusterName string) string { 57 split := strings.Split(complexClusterName, "_") 58 return split[len(split)-1] 59 } 60 61 // GetSafeUsername returns username by checking the active configuration 62 func GetSafeUsername(username string) string { 63 if strings.Contains(username, "Your active configuration is") { 64 return strings.Split(username, "\n")[1] 65 } 66 return username 67 } 68 69 // IsInCluster tells if we are running incluster 70 func IsInCluster() bool { 71 _, err := rest.InClusterConfig() 72 if err != nil { 73 return false 74 } 75 return true 76 }