Golang通过client-go操作Kubernetes资源需先初始化clientset(支持kubeconfig或in-cluster配置),再调用CoreV1Client等执行CRUD;自定义资源用dynamic.Client,监听变化则依赖Informer实现高效List-Watch。
用 Golang 通过 client-go 操作 Kubernetes 资源,核心是构建 REST 客户端、获取配置、实例化对应资源的客户端(如 CoreV1Client),再调用增删改查方法。关键在于正确初始化 clientset,并理解 Scheme、RESTClient 和 Informer 的分工。
最常用的是从 kubeconfig 文件或 in-cluster 配置加载 REST 配置,再生成 clientset:
rest.InClusterConfig()(Pod 内)或 clientcmd.BuildConfigFromFlags("", kubeconfigPath)(本地 ~/.kube/config)kubernetes.NewForConfig(cfg) 得到 *kubernetes.Clientset,它聚合了所有内置资源的客户端,比如 clientset.CoreV1().Pods("default")
拿到 clientset 后,按 Group/Version/Resource 分层访问。例如操作 Pod:
clientset.CoreV1().Pods("default").Create(ctx, podObj, metav1.CreateOptions{}),其中 podObj 是 *corev1.Pod 类型,需设置 ObjectMeta.Name、Spec.Containers 等字段clientset.CoreV1().Pods("default").Get(ctx, "my-pod", metav1.GetOptions{})
clientset.CoreV1().Pods("default").Update(ctx, updatedPod, metav1.UpdateOptions{})(注意要带 ResourceVersion)clientset.CoreV1().Pods("default").Delete(ctx, "my-pod", metav1.DeleteOptions{})
对于非内置资源(如 ingressroute.contour.io),不能直接用 clientset,需用 dynamic.Interface:
dynamic.NewForConfig(cfg) 初始化 dynamic clientschema.GroupVersionResource,例如 contourv1alpha1.SchemeGroupVersion.WithResource("ingressroutes")
dynamicClient.Resource(gvr).Namespace("default").Create(...),传入 unstructured.Unstructured 对
象轮询 API Server 效率低且易丢事件。Informer 封装了 List-Watch 机制,自动重连、缓存本地对象、触发事件回调:
cache.NewSharedIndexInformer 或更常用的 cache.NewSharedInformer,传入 ListWatch(通常由 clientset.CoreV1().Pods("").ListWatch 构造)AddFunc、UpdateFunc、DeleteFunc 处理事件Informer.Run(stopCh),并用 cache.WaitForCacheSync 确保初始数据同步完成workqueue.RateLimitingInterface 做事件去重与限流