As a full-time developer of microservices deployed to Kubernetes, I find myself often performing similar repetitive actions when debugging software. Sometimes I want to quickly try out a new Docker image on Kubernetes without writing a new Helm chart, or assign a Service object via NodePorts in order to connect a debugging tool, or manually add an annotation to a Kubernetes resource to trigger an action from an operator. There are some great open source products for many of these use cases, but not all of them. To improve my quality of life, I have started writing custom command-line interface (CLI) tools to automate such tasks. The combination of Go and the Kubernetes client APIs make it easy to create a new Kubernetes CLI.

Accessing KUBECONFIG with client-go

kubeconfig file is used to specify information about K8 clusters, users, namespaces, and authentication mechanisms. The kubectl tool uses kubeconfig files to find the information it needs to communicate with the API server of a K8 cluster.

Our custom CLI also needs access to a kubeconfig file to communicate with a K8 cluster. The client-go API makes it straightforward to read a user’s kubeconfig file.

package client

	import (
	    "k8s.io/client-go/kubernetes"
	    "k8s.io/client-go/rest"
	    "k8s.io/client-go/tools/clientcmd"
	    clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
	)

	// GetLocal reads a user's KUBECONFIG file and returns a Client interface, a REST interface, and current namespace
	func GetLocal() (*kubernetes.Clientset, *rest.Config, string, error) {
	    var err error

	    clientConfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
	        clientcmd.NewDefaultClientConfigLoadingRules(),
	        &clientcmd.ConfigOverrides{ClusterInfo: clientcmdapi.Cluster{Server: ""}})

	    namespace, _, err := clientConfig.Namespace()
	    if err != nil {
	        return nil, nil, "", err
	    }

	    config, err := clientConfig.ClientConfig()
	    if err != nil {
	        return nil, nil, "", err
	    }

	    client, err := kubernetes.NewForConfig(config)
	    if err != nil {
	        return nil, nil, "", err
	    }
	    return client, config, namespace, nil
	}

#kubernetes #kubectl #go #cli #microservices

Writing a Kubernetes CLI in Go
1.15 GEEK