Ask Your Question
4

What is the method to remove all custom resources of a specific type in a k8s cluster, including all namespaces, using client-go?

asked 2023-06-10 23:04:44 +0000

devzero gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by » oldest newest most voted
1

answered 2023-06-10 23:28:02 +0000

bukephalos gravatar image

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!

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-10 23:04:44 +0000

Seen: 23 times

Last updated: Jun 10 '23