How to delete k8s resource objects in batch

This article was first published on the public account [my little bowl soup] to scan the QR code at the end of the article for attention, exchange and study together

In cloud platform development and middleware containerization, there is often a need to delete k8s resource objects in batches. Here are some examples of kubectl and golang sending requests to delete pvc, pv and pod for subsequent learning and reference.

kubectl sends delete request

Delete pod in batch according to label:

kubectl delete pod -n kube-system -l "harmonycloud.cn/statefulset=redis-ll-1010-a"

Batch delete pvc according to label:

kubectl delete pvc -n kube-system -l "harmonycloud.cn/statefulset=redis-ll-1010-a"

Delete pv in batch according to label:

kubectl delete pv -l "harmonycloud.cn/statefulset=redis-ll-1010-a"

golang sends deletion requests

Delete pvc, pod and pv in batches according to label

Note: add the following parameters to the startup parameters:

--kubeconfig=/root/.kube/config --v=5
package operator

import (
    "flag"
    extensionsclient "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
    "k8s.io/apimachinery/pkg/api/errors"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "k8s.io/apimachinery/pkg/labels"
    "k8s.io/apiserver/pkg/util/logs"
    clientset "k8s.io/client-go/kubernetes"
    restclient "k8s.io/client-go/rest"
    "k8s.io/client-go/tools/clientcmd"
    "k8s.io/klog"
    "os"
    "testing"
)

type OperatorManagerServer struct {
    Master     string
    Kubeconfig string
}

func NewOMServer() *OperatorManagerServer {
    s := OperatorManagerServer{}
    return &s
}

var s *OperatorManagerServer

func init() {

    s = NewOMServer()
    flag.StringVar(&s.Master, "master", s.Master, "The address of the Kubernetes API server (overrides any value in kubeconfig)")
    flag.StringVar(&s.Kubeconfig, "kubeconfig", s.Kubeconfig, "Path to kubeconfig file with authorization and master location information.")
    //Initialize klog and other flag s
    logs.InitLogs()
    flag.Parse()
}

func Test_DeleteCollection(t *testing.T) {
    if err := Run(s); err != nil {
        t.Fatalf("%v\n", err)
        os.Exit(1)
    }
}

func Run(s *OperatorManagerServer) error {

    var (
        generalLabelKey       = "harmonycloud.cn/statefulset"
        redisClusterName      = "redis-ll-1010"
        redisClusterNamespace = "kube-system"
    )

    kubeClient, _, _, err := createClients(s)

    if err != nil {
        return err
    }

    //Delete pod in batches according to label
    labelPod := labels.SelectorFromSet(labels.Set(map[string]string{generalLabelKey: redisClusterName}))
    listPodOptions := metav1.ListOptions{
        LabelSelector: labelPod.String(),
    }
    err = kubeClient.CoreV1().Pods(redisClusterNamespace).DeleteCollection(&metav1.DeleteOptions{}, listPodOptions)
    if err != nil {
        if !errors.IsNotFound(err) {
            klog.Errorf("Drop RedisCluster: %v/%v pod error: %v", redisClusterNamespace, redisClusterName, err)
            return err
        }
    }

    //Batch delete pvc according to label
    labelPvc := labels.SelectorFromSet(labels.Set(map[string]string{"app": redisClusterName}))
    listPvcOptions := metav1.ListOptions{
        LabelSelector: labelPvc.String(),
    }
    err = kubeClient.CoreV1().PersistentVolumeClaims(redisClusterNamespace).DeleteCollection(&metav1.DeleteOptions{}, listPvcOptions)
    if err != nil {
        if !errors.IsNotFound(err) {
            klog.Errorf("Drop RedisCluster: %v/%v pvc error: %v", redisClusterNamespace, redisClusterName, err)
            return err
        }
    }

    //If pv is not deleted, delete
    labelPv := labels.SelectorFromSet(labels.Set(map[string]string{generalLabelKey: redisClusterName}))
    listPvOptions := metav1.ListOptions{
        LabelSelector: labelPv.String(),
    }
    err = kubeClient.CoreV1().PersistentVolumes().DeleteCollection(&metav1.DeleteOptions{}, listPvOptions)

    if err != nil {
        if !errors.IsNotFound(err) {
            klog.Errorf("Drop RedisCluster: %v/%v pv error: %v", redisClusterNamespace, redisClusterName, err)
            return err
        }
    }

    return nil
}

//Create client according to kubeconfig file
func createClients(s *OperatorManagerServer) (*clientset.Clientset, *extensionsclient.Clientset, *restclient.Config, error) {
    kubeconfig, err := clientcmd.BuildConfigFromFlags(s.Master, s.Kubeconfig)
    if err != nil {
        return nil, nil, nil, err
    }

    kubeconfig.QPS = 100
    kubeconfig.Burst = 100

    kubeClient, err := clientset.NewForConfig(restclient.AddUserAgent(kubeconfig, "operator-manager"))
    if err != nil {
        klog.Fatalf("Invalid API configuration: %v", err)
    }

    extensionClient, err := extensionsclient.NewForConfig(restclient.AddUserAgent(kubeconfig, "operator-manager"))
    if err != nil {
        klog.Fatalf("Invalid API configuration: %v", err)
    }

    return kubeClient, extensionClient, kubeconfig, nil
}

Provided in client go

  • The Delete method can only Delete a single resource object. The first parameter is usually the name of the resource object. The second parameter is the Delete option, such as grace period seconds, Delete propagation policy: Foreground Delete, Background Delete, Orphan Delete, Orphan Delete.
  • The first parameter of the DeleteCollection method is the delete option, and the second parameter is the delete condition, including label Selector, field Selector, etc.
Delete(name string, options *metav1.DeleteOptions) error
DeleteCollection(options *metav1.DeleteOptions, listOptions metav1.ListOptions) error

Reference resources

k8s official API document:

https://kubernetes.io/docs/re...

This public account provides free csdn download service and massive it learning resources. If you are ready to enter the IT pit and aspire to become an excellent program ape, these resources are suitable for you, including but not limited to java, go, python, springcloud, elk, embedded, big data, interview materials, front-end and other resources. At the same time, we have set up a technology exchange group. There are many big guys who will share technology articles from time to time. If you want to learn and improve together, you can reply [2] in the background of the public account. Free invitation plus technology exchange groups will learn from each other and share programming it related resources from time to time.

Scan the code to pay attention to the wonderful content and push it to you at the first time

Keywords: Go Redis Kubernetes REST Java

Added by obsidian on Wed, 16 Oct 2019 05:11:19 +0300