1 | initial version |
To remove all custom resources of a specific type in a k8s cluster, including all namespaces, using client-go, you can follow the below steps:
config, err := rest.InClusterConfig()
if err != nil {
// handle error
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
// handle error
}
listOptions := metav1.ListOptions{}
customResourceList, err := clientset.CustomResourceDefinitions().List(listOptions)
if err != nil {
// handle error
}
for _, crd := range customResourceList.Items {
if crd.Spec.Names.Kind == "CustomResourceKind" {
customResourceName := crd.ObjectMeta.Name
// code to remove the custom resource
}
}
customResourceName
to remove the custom resource from all the namespaces. You can use the below code to remove the custom resource from all the namespaces:// get list of namespaces
namespaceList, err := clientset.CoreV1().Namespaces().List(listOptions)
if err != nil {
// handle error
}
// loop through namespaces and delete the custom resource
for _, namespace := range namespaceList.Items {
err = clientset.
Dynamic().
Resource(schema.GroupVersionResource{
Group: "custom.resource.group",
Version: "v1alpha1",
Resource: "customresourcekinds",
}).
Namespace(namespace.Name).
Delete(context.Background(), customResourceName, metav1.DeleteOptions{})
if err != nil {
// handle error
}
}
Hope this helps!