英文:
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 := &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(), &item)
if err != nil {
return err
}
}
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论