Search code examples
kubernetesamazon-ekskubernetes-pvc

Delete Kubernetes PVC ebs volumes in batch


I have more than 4000 pvc in my kubernetes aws eks cluster.

  • From those 4000+ pvc I have to delete almost 3999 pvcs

Now instead of using command:

kubetcl delete pvc pvc-data-name

and delete every pvc separately which can take me sooo long.. I want to find a way to delete them in batches or all together.


Solution

  • you can try this one.

    kubectl delete pvc --field-selector metadata.name!=<name-dont-want-to-delete-1>, metadata.name!=<name-dont-want-to-delete-2>, metadata.name!=<name-dont-want-to-delete-3>
    

    or, also you can do this with go-client. to do this with go client see the document Ref

    i have added a label in every pvc that i don't want to delete.

      labels:
        test: test-1
    
    
    import (
       "context"
       "fmt"
       metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    
       "k8s.io/client-go/kubernetes"
       "k8s.io/client-go/util/homedir"
       "kmodules.xyz/client-go/tools/clientcmd"
       "log"
       "path/filepath"
    )
    
    func testFunc() ( error) {
       masterURL := ""
    
       kubeconfigPath := filepath.Join(homedir.HomeDir(), ".kube", "config")
    
    
    
       config, err := clientcmd.BuildConfigFromFlags(masterURL, kubeconfigPath)
       if err != nil {
           log.Fatalf("Could not get Kubernetes config: %s", err)
       }
    
       kc := kubernetes.NewForConfigOrDie(config)
       labelSelector := &metav1.LabelSelector{
           MatchExpressions: []metav1.LabelSelectorRequirement{
               {
                   "test",
                   metav1.LabelSelectorOpNotIn,
                   []string{
                       "test-0",
                       "test-1",
                   },
               },
           },
       }
       err = kc.CoreV1().PersistentVolumeClaims("default").DeleteCollection(context.TODO(), metav1.DeleteOptions{}, metav1.ListOptions{
           LabelSelector: metav1.FormatLabelSelector(labelSelector),
       })
       fmt.Println(err)
       
       return  nil
    }