You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用client-go v0.17.3删除全部或指定标签的Kubernetes资源?

Answers to Your client-go v0.17.3 Kubernetes Deletion Questions

Hey there! Let's tackle your two questions about deleting Kubernetes resources with client-go v0.17.3, including replicating that handy kubectl command you mentioned.


1. How to Delete All Kubernetes Resources with client-go?

client-go doesn't have a single "delete everything" method out of the box—you'll need to iterate over all resource types that support deletion, then delete their instances. There are two common approaches: using the dynamic client (more flexible for all resource types) or using the typed Clientset (which requires handling each resource group/version explicitly, like the struct you shared).

The dynamic client lets you interact with any Kubernetes resource without pre-generated types, making it perfect for replicating the kubectl delete $(kubectl api-resources --verbs=delete...) behavior:

package main

import (
	"context"
	"fmt"
	"log"
	"strings"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/client-go/dynamic"
	"k8s.io/client-go/tools/clientcmd"
)

func main() {
	// Load kubeconfig (adjust path as needed)
	config, err := clientcmd.BuildConfigFromFlags("", clientcmd.RecommendedHomeFile)
	if err != nil {
		log.Fatal(err)
	}

	// Create dynamic client
	dynClient, err := dynamic.NewForConfig(config)
	if err != nil {
		log.Fatal(err)
	}

	// Get all API resources that support DELETE verb
	discoveryClient, err := dynamic.NewDiscoveryClientForConfig(config)
	if err != nil {
		log.Fatal(err)
	}
	apiResources, err := discoveryClient.ServerPreferredResources()
	if err != nil {
		log.Fatal(err)
	}

	// Iterate over each resource type
	for _, resourceList := range apiResources {
		gv, err := schema.ParseGroupVersion(resourceList.GroupVersion)
		if err != nil {
			continue
		}
		for _, res := range resourceList.APIResources {
			// Skip resources that don't support DELETE or are cluster-scoped (optional)
			if !contains(res.Verbs, "delete") || !res.Namespaced {
				continue
			}

			gvr := schema.GroupVersionResource{
				Group:    gv.Group,
				Version:  gv.Version,
				Resource: res.Name,
			}

			// Delete all instances in the default namespace (change to metav1.NamespaceAll for all namespaces)
			err := dynClient.Resource(gvr).Namespace("default").DeleteCollection(
				context.TODO(),
				metav1.DeleteOptions{},
				metav1.ListOptions{},
			)
			if err != nil {
				log.Printf("Failed to delete %s: %v", res.Name, err)
			} else {
				fmt.Printf("Deleted all %s resources\n", res.Name)
			}
		}
	}
}

func contains(slice []string, item string) bool {
	for _, s := range slice {
		if s == item {
			return true
		}
	}
	return false
}

Using the Typed Clientset (Explicit Resource Handling)

If you prefer using the Clientset struct you shared, you'll need to write code for each resource group/version. Here's an example for a few common resources:

package main

import (
	"context"
	"log"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/clientcmd"
)

func main() {
	config, err := clientcmd.BuildConfigFromFlags("", clientcmd.RecommendedHomeFile)
	if err != nil {
		log.Fatal(err)
	}

	clientset, err := kubernetes.NewForConfig(config)
	if err != nil {
		log.Fatal(err)
	}

	// Delete all Pods in default namespace
	err = clientset.CoreV1().Pods("default").DeleteCollection(
		context.TODO(),
		metav1.DeleteOptions{},
		metav1.ListOptions{},
	)
	if err != nil {
		log.Printf("Failed to delete Pods: %v", err)
	}

	// Delete all Deployments in default namespace
	err = clientset.AppsV1().Deployments("default").DeleteCollection(
		context.TODO(),
		metav1.DeleteOptions{},
		metav1.ListOptions{},
	)
	if err != nil {
		log.Printf("Failed to delete Deployments: %v", err)
	}

	// Repeat this pattern for other resources from the Clientset (Services, ConfigMaps, etc.)
}

2. Can client-go v0.17.3 Delete All Resources with a Specific Label?

Absolutely! You just need to add a LabelSelector to your ListOptions when calling DeleteCollection. This works with both the dynamic client and the typed Clientset.

Example: Delete Resources with Label app=my-app

Using Dynamic Client

Modify the ListOptions in the dynamic client code above:

listOpts := metav1.ListOptions{
	LabelSelector: "app=my-app",
}

err := dynClient.Resource(gvr).Namespace("default").DeleteCollection(
	context.TODO(),
	metav1.DeleteOptions{},
	listOpts,
)

Using Typed Clientset

For a specific resource like Deployments:

err = clientset.AppsV1().Deployments("default").DeleteCollection(
	context.TODO(),
	metav1.DeleteOptions{},
	metav1.ListOptions{
		LabelSelector: "app=my-app",
	},
)

This will only delete resources that match the specified label selector, just like kubectl delete all -l app=my-app.


Key Notes for v0.17.3

  • The DeleteCollection method is available in all typed clients (like CoreV1, AppsV1) in v0.17.3, so you don't have to worry about missing functionality.
  • Cluster-scoped resources (like Namespaces, Nodes) can be deleted by omitting the Namespace call (or using metav1.NamespaceAll for namespaced resources across all namespaces).

内容的提问来源于stack exchange,提问作者aliench0

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 11:57:50