k8s client-go 02操作k8s deployment

Clientset

  构造clientset操作k8s集群。

package main

import (
    "context"
    "fmt"
    v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "k8s.io/client-go/kubernetes"
    "k8s.io/client-go/tools/clientcmd"
    "log"
)

func main() {
    // 1. 构造访问config的配置,从文件中加载,将 home目录下的 .kube/config拷贝到当前./conf/下
    config, err := clientcmd.BuildConfigFromFlags("", "./conf/config")
    if err != nil {
        panic(err)
    }

    // 2. 创建clientset
    clientset, err := kubernetes.NewForConfig(config)
    if err != nil {
        panic(err)
    }

    // 3.对资源对象进行操作
    podList, err := clientset.CoreV1().Pods("dev").List(context.Background(), v1.ListOptions{})
    if err != nil {
        log.Printf("list pods error:%v\n", err)
        return
    }

    fmt.Println("dev pod count:", len(podList.Items))
    for _, pod := range podList.Items {
        fmt.Printf("name: %s\n", pod.Name)
    }
}

使用clientset创建pod

package main

import (
    "context"
    corev1 "k8s.io/api/core/v1"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "k8s.io/client-go/kubernetes"
    "k8s.io/client-go/tools/clientcmd"
    "log"
)

func main() {
    // 1. 构造访问config的配置,从文件中加载,将 home目录下的 .kube/config拷贝到当前./conf/下
    config, err := clientcmd.BuildConfigFromFlags("", "./conf/config")
    if err != nil {
        panic(err)
    }

    // 2. 创建clientset
    clientset, err := kubernetes.NewForConfig(config)
    if err != nil {
        panic(err)
    }

    // 3.创建一个pod对象并填上字段
    pod := corev1.Pod{
        TypeMeta: metav1.TypeMeta{
            APIVersion: "v1",
            Kind:       "Pod",
        },
        ObjectMeta: metav1.ObjectMeta{
            Name:      "nginx",
            Namespace: "default",
            Labels: map[string]string{
                "run": "nginx",
            },
        },
        Spec: corev1.PodSpec{
            Containers: []corev1.Container{
                {
                    Image: "nginx",
                    Name:  "nginx-container",
                    Ports: []corev1.ContainerPort{
                        {
                            ContainerPort: 80,
                        },
                    },
                },
            },
        },
    }

    // 4. 创建pod
    _, err = clientset.CoreV1().Pods("default").Create(context.Background(), &pod, metav1.CreateOptions{})
    if err != nil {
        log.Printf("create pod error:%v\n", err)
        return
    }
    log.Printf("create pod success\n")
}

创建、更新、查询、删除Deployment

  使用client-go,实现一个deployment的创建、更新和删除操作。代码依据官方的例子修改而来

package main

import (
    "bufio"
    "context"
    "fmt"
    appsv1 "k8s.io/api/apps/v1"
    corev1 "k8s.io/api/core/v1"
    v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "k8s.io/client-go/kubernetes"
    appsresv1 "k8s.io/client-go/kubernetes/typed/apps/v1"
    "k8s.io/client-go/tools/clientcmd"
    "k8s.io/client-go/util/retry"
    "k8s.io/klog/v2"
    "os"
)

func main() {
    // 1、创建配置文件
    config, err := clientcmd.BuildConfigFromFlags("", "./conf/config")
    if err != nil {
        panic(err)
    }

    // 2、创建clientset
    clientset, err := kubernetes.NewForConfig(config)
    if err != nil {
        panic(err)
    }
    deployClient := clientset.AppsV1().Deployments(corev1.NamespaceDefault)
    
    // 3、创建deployment
    CreateDeploy(deployClient)

    prompt()
    // 4、更新deployment
    UpdateDeploy(deployClient)

    prompt()
    // 5、查询deployment
    ListDeploy(deployClient)

    prompt()
    // 6、删除deployment
    DeleteDeploy(deployClient)
}

func CreateDeploy(client appsresv1.DeploymentInterface) {
    klog.Info("CreateDeploy...........")
    replicas := int32(2)
    deploy := appsv1.Deployment{
        TypeMeta: v1.TypeMeta{
            Kind:       "Deployment",
            APIVersion: "apps/v1",
        },
        ObjectMeta: v1.ObjectMeta{
            Name:      "deploy-nginx-demo",
            Namespace: corev1.NamespaceDefault,
        },
        Spec: appsv1.DeploymentSpec{
            Replicas: &replicas,
            Selector: &v1.LabelSelector{
                MatchLabels: map[string]string{
                    "app": "nginx",
                },
            },
            Template: corev1.PodTemplateSpec{
                ObjectMeta: v1.ObjectMeta{
                    Name: "nginx",
                    Labels: map[string]string{
                        "app": "nginx",
                    },
                },
                Spec: corev1.PodSpec{
                    Containers: []corev1.Container{
                        {
                            Name:  "web",
                            Image: "nginx:1.12",
                            Ports: []corev1.ContainerPort{
                                {
                                    Protocol:      corev1.ProtocolTCP,
                                    ContainerPort: 80,
                                },
                            },
                        },
                    },
                },
            },
        },
    }

    dep, err := client.Create(context.Background(), &deploy, v1.CreateOptions{})
    if err != nil {
        klog.Errorf("create deployment error:%v", err)
        return
    }
    klog.Infof("create deployment success, name:%s", dep.Name)
}

func UpdateDeploy(client appsresv1.DeploymentInterface) {
    klog.Info("UpdateDeploy...........")
    // 当有多个客户端对同一个资源进行操作时,可能会发生错误。使用RetryOnConflict来重试,重试相关参数由DefaultRetry来提供
    err := retry.RetryOnConflict(retry.DefaultRetry, func() error {
        // 查询要更新的deploy
        deploy, err := client.Get(context.Background(), "deploy-nginx-demo", v1.GetOptions{})
        if err != nil {
            klog.Errorf("can't get deployment, err:%v", err)
            return nil
        }

        // 修改参数后进行更新
        replicas := int32(1)
        deploy.Spec.Replicas = &replicas
        deploy.Spec.Template.Spec.Containers[0].Image = "nginx:1.13"

        _, err = client.Update(context.Background(), deploy, v1.UpdateOptions{})
        if err != nil {
            klog.Errorf("update deployment error, err:%v", err)
        }
        return err
    })

    if err != nil {
        klog.Errorf("update deployment error, err:%v", err)
    } else {
        klog.Infof("update deployment success")
    }

}

func ListDeploy(client appsresv1.DeploymentInterface) {
    klog.Info("ListDeploy...........")
    deplist, err := client.List(context.Background(), v1.ListOptions{})
    if err != nil {
        klog.Errorf("list deployment error, err:%v", err)
        return
    }

    for _, dep := range deplist.Items {
        klog.Infof("deploy name:%s, replicas:%d, container image:%s", dep.Name, *dep.Spec.Replicas, dep.Spec.Template.Spec.Containers[0].Image)
    }
}

func DeleteDeploy(client appsresv1.DeploymentInterface) {
    klog.Info("DeleteDeploy...........")
    // 删除策略
    deletePolicy := v1.DeletePropagationForeground
    err := client.Delete(context.Background(), "deploy-nginx-demo", v1.DeleteOptions{PropagationPolicy: &deletePolicy})
    if err != nil {
        klog.Errorf("delete deployment error, err:%v", err)
    } else {
        klog.Info("delete deployment success")
    }
}

func prompt() {
    fmt.Printf("-> Press Return key to continue.")
    scanner := bufio.NewScanner(os.Stdin)
    for scanner.Scan() {
        break
    }
    if err := scanner.Err(); err != nil {
        panic(err)
    }
    fmt.Println()
}

 

posted @ 2023-01-29 15:31  wushaoyu  阅读(697)  评论(0编辑  收藏  举报