首页 > 其他分享 >k8s client-go 02基础clientset操作k8s

k8s client-go 02基础clientset操作k8s

时间:2023-01-29 15:48:19浏览次数:52  
标签:02 klog err nil v1 client k8s

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

 

标签:02,klog,err,nil,v1,client,k8s
From: https://www.cnblogs.com/wushaoyu/p/17072810.html

相关文章

  • k8s client-go 01介绍
    关于client-goclient-go是一个golang的client,我们可以通过client-go与K8SapiServer进行交互,对k8s集群中资源对象,包括内置资源(例如:Pod、Deployment、Service等)和CRD进......
  • vSphereClient整合失败的诡异事件
    20230129-jenkiens服务器突然启动失败,根据网上说法是删除快照后进行整合删除快照还蛮简单的,很快就解决了,但整合时一直报错从晚上6点开始尝试到9点后无奈放弃,第二天早上起......
  • 2023考试计划
    初级会计职称报名时间“2023年初级会计职称考试报名时间为2023年2月7日至2月28日,......
  • k8s v1.24.1 配置 cephfs
    本地环境情况角色IP版本k8s-master-1172.16.16.108K8Sv1.24.1,containerd://1.6.8k8s-node-1172.16.16.109K8Sv1.24.1,containerd://1.6.8k8s-no......
  • Firefly-RK356x板卡专栏总目录(Update to 2022.07.02)
    ......
  • <Web Navigation> stack-POJ1028
    WebNavigationTimeLimit: 1000MS MemoryLimit: 10000KTotalSubmissions: 41995 Accepted: 18687DescriptionStandardwebbrowserscontainf......
  • Good Bye 2022 简要题解
    从这里开始比赛目录过气选手留下了只会套路的眼泪。sad......ProblemA KoxiaandWhiteboards相信大家都会.jpgCode#include<bits/stdc++.h>using......
  • 2023牛客寒假算法基础集训营2
    《重点考察容斥原理的题目》  《L.TokitsukazeandThreeIntegers》  可以看的出:n很小,首先考虑暴力的方法:我们可以用两层for循环,将(ai*aj)%p......
  • 2023年学技术为什么选择邯郸翱翔
    ​春节休息放松之后整理好心情,调整好状态“满电”投入新一年的工作与学习当中吧!春季班火热开启,年后该为自己打算了作为初中生或者高中生,如果你的文化课成绩不理想的话,选择学......
  • Prometheus监控K8S各项指标
    一、Node监控1、内存指标#Node总内存大小:node_memory_MemTotal_bytes{instance="ec2-13-213-40-179.ap-southeast-1.compute.amazonaws.com:9100",job="node"}#Node......