Ask Your Question

Revision history [back]

click to hide/show revision 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:

  1. First, you need to create a clientset to communicate with the k8s cluster. You can use the below code to create the clientset:
config, err := rest.InClusterConfig()
if err != nil {
    // handle error
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
    // handle error
}
  1. Once you have the clientset, you can use it to list all the custom resources of the specific type in all the namespaces. You can use the below code to list all the custom resources of the specific type:
listOptions := metav1.ListOptions{}
customResourceList, err := clientset.CustomResourceDefinitions().List(listOptions)
if err != nil {
    // handle error
}
  1. Once you have the custom resource list, you can loop through it to get the name of each custom resource. Use the below code to loop through the custom resource list:
for _, crd := range customResourceList.Items {
    if crd.Spec.Names.Kind == "CustomResourceKind" {
        customResourceName := crd.ObjectMeta.Name
        // code to remove the custom resource
    }
}
  1. In the above loop, you can use the 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
    }
}
  1. Replace the value “CustomResourceKind” with the kind of custom resource for which you want to remove all occurrences.

Hope this helps!