How to delete all custom resources of a kind in k8s cluster (all namespaces) using client-go

huangapple go评论76阅读模式
英文:

How to delete all custom resources of a kind in k8s cluster (all namespaces) using client-go

问题

我正在尝试使用client-go在k8s集群中删除特定类型的资源。

我正在使用以下代码,但它需要声明一个特定的命名空间,但我想在所有命名空间中删除此资源。

	u.SetName("test")
	u.SetNamespace(v1.NamespaceAll)
	u.SetGroupVersionKind(schema.GroupVersionKind{
		Group:   "group",
		Kind:    "kind",
		Version: "v1",
	})
	err := k8sClient.Delete(context.TODO(), u)

	if err != nil {
		fmt.Println(err.Error())
		return err
	}

在这里找到了示例 - https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client
但它没有提到关于所有命名空间的内容。
请问有人可以提供一种解决方法吗?

注意:
这是自定义资源,不是默认的类型,如pod或deployment等。

英文:

I'm trying to delete resources of a particular kind in a k8s cluster using client-go.

I'm using this code but it requires a specific namespace to be declared, but i want to delete this resource in all namespaces.

	u.SetName("test")
	u.SetNamespace(v1.NamespaceAll)
	u.SetGroupVersionKind(schema.GroupVersionKind{
		Group:   "group",
		Kind:    "kind",
		Version: "v1",
	})
	err := k8sClient.Delete(context.TODO(), u)

	if err != nil {
		fmt.Println(err.Error())
		return err
	}

Found the example here - https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client
but it doesn't mention anything about all namespaces.
Could someone plz provide a way to figure this out.

NOTE:
This is custom resource. not default kind such as pod or deployment etc

答案1

得分: 1

使用List方法获取所有命名空间中所有资源的列表,然后循环遍历该列表,并使用Delete方法删除每个资源。

cr := &v1alpha1.CustomResource{}

// 获取所有命名空间中您自定义资源的所有实例的列表
listOpts := []client.ListOption{
    client.InNamespace(v1.NamespaceAll),
}

err := k8sClient.List(context.Background(), cr, listOpts...)
if err != nil {
    return err
}

// 循环遍历列表并删除每个自定义资源的实例
for _, item := range cr.Items {
    err = k8sClient.Delete(context.Background(), &item)
    if err != nil {
        return err
    }
}
英文:

Use the List method to get a list of all resources in all namespaces and then loop through the list and delete each resource using the Delete method.

<!-- language: lang-js -->

cr := &amp;v1alpha1.CustomResource{}

// Get a list of all instances of your custom resource in all namespaces
listOpts := []client.ListOption{
    client.InNamespace(v1.NamespaceAll),
}

err := k8sClient.List(context.Background(), cr, listOpts...)
if err != nil {
    return err
}

// Loop through the list and delete each instance of your custom resource
for _, item := range cr.Items {
    err = k8sClient.Delete(context.Background(), &amp;item)
    if err != nil {
        return err
    }
}

<!-- end snippet -->

huangapple
  • 本文由 发表于 2022年1月14日 19:31:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/70709946.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定