github.com/darmach/terratest@v0.34.8-0.20210517103231-80931f95e3ff/modules/k8s/client.go (about) 1 package k8s 2 3 import ( 4 "k8s.io/client-go/kubernetes" 5 "k8s.io/client-go/rest" 6 7 // The following line loads the gcp plugin which is required to authenticate against GKE clusters. 8 // See: https://github.com/kubernetes/client-go/issues/242 9 _ "k8s.io/client-go/plugin/pkg/client/auth/gcp" 10 11 "github.com/gruntwork-io/terratest/modules/logger" 12 "github.com/gruntwork-io/terratest/modules/testing" 13 ) 14 15 // GetKubernetesClientE returns a Kubernetes API client that can be used to make requests. 16 func GetKubernetesClientE(t testing.TestingT) (*kubernetes.Clientset, error) { 17 kubeConfigPath, err := GetKubeConfigPathE(t) 18 if err != nil { 19 return nil, err 20 } 21 22 options := NewKubectlOptions("", kubeConfigPath, "default") 23 return GetKubernetesClientFromOptionsE(t, options) 24 } 25 26 // GetKubernetesClientFromOptionsE returns a Kubernetes API client given a configured KubectlOptions object. 27 func GetKubernetesClientFromOptionsE(t testing.TestingT, options *KubectlOptions) (*kubernetes.Clientset, error) { 28 var err error 29 var config *rest.Config 30 31 kubeConfigPath, err := options.GetConfigPath(t) 32 if err != nil { 33 return nil, err 34 } 35 logger.Logf(t, "Configuring kubectl using config file %s with context %s", kubeConfigPath, options.ContextName) 36 // Load API config (instead of more low level ClientConfig) 37 config, err = LoadApiClientConfigE(kubeConfigPath, options.ContextName) 38 if err != nil { 39 logger.Logf(t, "Error loading api client config, falling back to in-cluster authentication via serviceaccount token: %s", err) 40 config, err = rest.InClusterConfig() 41 if err != nil { 42 return nil, err 43 } 44 logger.Log(t, "Configuring kubectl using in-cluster serviceaccount token") 45 } 46 47 clientset, err := kubernetes.NewForConfig(config) 48 if err != nil { 49 return nil, err 50 } 51 52 return clientset, nil 53 }