adi*_*tya 5 go kubernetes 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
}
Run Code Online (Sandbox Code Playgroud)
在这里找到了示例 - https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client 但它没有提及有关所有命名空间的任何内容。有人可以提供一种方法来解决这个问题吗?
注意:这是自定义资源。不是默认类型,例如 pod 或部署等
小智 2
使用该List方法获取所有资源的列表all namespaces,然后循环该列表并使用该Delete方法删除每个资源。
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
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1931 次 |
| 最近记录: |