import ( "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" "k8s.io/kubernetes/pkg/kubectl/cmd/util/factory" ) func ConnectToKubernetesCluster() (*kubernetes.Clientset, error) { config, err := rest.InClusterConfig() if err != nil { return nil, err } factory := factory.NewMatchVersionFlags(factory.NewConfigFlags(false)) clientset, err := kubernetes.NewForConfig(config) if err != nil { return nil, err } factory.SetClientset(clientset) return clientset, nil }
import ( "k8s.io/client-go/kubernetes/scheme" "k8s.io/kubernetes/pkg/kubectl/cmd/util/factory" ) func GetDeploymentForNamespace(factory factory.ClientMapperForCommand, namespace string, deploymentName string) (*appsv1.Deployment, error) { deployment, err := factory.DynamicClient().Resource(schema.GroupVersionResource{ Group: "apps", Version: "v1", Resource: "deployments", }).Namespace(namespace).Get(deploymentName, metav1.GetOptions{}) if err != nil { return nil, err } return deployment.(*appsv1.Deployment), nil }In the above example, the GetDeploymentForNamespace() method maps the command-line arguments and settings into a client request to get a deployment object from Kubernetes. It uses the DynamicClient() method of the ClientMapperForCommand interface to create a dynamic client that can work with any Kubernetes resources. In conclusion, the k8s.io/kubernetes/pkg/kubectl/cmd/util package library provides a set of interfaces and tools for managing Kubernetes resources from the command-line. It is widely used in the Kubernetes ecosystem to write custom controllers, CLI tools, and automation scripts.