gokubernetesclient-go

How to delete all custom resources of a kind in k8s cluster (all namespaces) using client-go


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


Solution

  • 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.

    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
        }
    }