github.com/someshkoli/terratest@v0.41.1/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  	if options.InClusterAuth {
    32  		config, err = rest.InClusterConfig()
    33  		if err != nil {
    34  			return nil, err
    35  		}
    36  		logger.Log(t, "Configuring Kubernetes client to use the in-cluster serviceaccount token")
    37  	} else {
    38  		kubeConfigPath, err := options.GetConfigPath(t)
    39  		if err != nil {
    40  			return nil, err
    41  		}
    42  		logger.Logf(t, "Configuring Kubernetes client using config file %s with context %s", kubeConfigPath, options.ContextName)
    43  		// Load API config (instead of more low level ClientConfig)
    44  		config, err = LoadApiClientConfigE(kubeConfigPath, options.ContextName)
    45  		if err != nil {
    46  			logger.Logf(t, "Error loading api client config, falling back to in-cluster authentication via serviceaccount token: %s", err)
    47  			config, err = rest.InClusterConfig()
    48  			if err != nil {
    49  				return nil, err
    50  			}
    51  			logger.Log(t, "Configuring Kubernetes client to use the in-cluster serviceaccount token")
    52  		}
    53  	}
    54  
    55  	clientset, err := kubernetes.NewForConfig(config)
    56  	if err != nil {
    57  		return nil, err
    58  	}
    59  
    60  	return clientset, nil
    61  }