关于kubernetes:clientgo连接kubernetes集群create

背景

client-go连贯kubernetes集群-connect and list。都是查看获取list列表的。当初想用client-go创立利用该如何操作呢?

client-go连贯kubernetes集群-create

创立一个namespace:

clientset.CoreV1().Namespaces().Create

package main

import (
    "context"
    "flag"
    "fmt"
    v1 "k8s.io/api/core/v1"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "k8s.io/client-go/kubernetes"
    "k8s.io/client-go/tools/clientcmd"
    "k8s.io/client-go/util/homedir"
    "path/filepath"
)

func main() {
    var kubeconfig *string
    if home := homedir.HomeDir(); home != "" {
        kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")
    } else {
        kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
    }
    flag.Parse()
    config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
    if err != nil {
        panic(err.Error())
    }

    // create the clientset
    clientset, err := kubernetes.NewForConfig(config)
    if err != nil {
        panic(err.Error())
    }
    namespace := &v1.Namespace{
        ObjectMeta: metav1.ObjectMeta{
            Name: "zhangpeng",
        },
    }
    result, err := clientset.CoreV1().Namespaces().Create(context.TODO(), namespace, metav1.CreateOptions{})
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Printf("Create ns %s SuccessFul !", result.ObjectMeta.Name)
        list, _ := clientset.CoreV1().Namespaces().List(context.Background(), metav1.ListOptions{})
        for _, item := range list.Items {
            fmt.Println(item.Name)

        }
    }
    //fmt.Println(clientset.ServerVersion())
    //list, _ := clientset.CoreV1().Namespaces().List(context.Background(), metav1.ListOptions{})
    //for _, item := range list.Items {
    //    fmt.Println(item.Name)
    //
    //}
    //fmt.Println("pod list in develop")
    //list1, _ := clientset.CoreV1().Pods("develop").List(context.Background(), metav1.ListOptions{})
    //for _, item := range list1.Items {
    //    fmt.Println(item.Name)
    //
    //}
    clientset.AppsV1()

}


嗯打印在一起了 也能够加个换行符?

创立一个deployment

deployment是属于appv1的apiversion.当然了Goland中corev1().前面能够试一下补全是没有deployment的选项的!



*v1.Deployment怎么解决呢?独自写一个deployment的yaml文件而后文件流读取?或者间接在go文件中定义deployment的配置?

生成yaml读取文件流的形式:

生成yaml文件

kubectl create deployment nginx --image=nginx -o yaml --dry-run=client >nginx.yaml

nginx.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  creationTimestamp: null
  labels:
    app: nginx
  name: nginx
spec:
  replicas: 1
  selector:
    matchLabels:
      app: nginx
  strategy: {}
  template:
    metadata:
      creationTimestamp: null
      labels:
        app: nginx
    spec:
      containers:
      - image: nginx
        name: nginx
        resources: {}
status: {}

将文件保留为src/yamls/nginx.yaml

main.go

package main

import (
    "context"
    "encoding/json"
    "flag"
    "fmt"
    "io/ioutil"
    v1 "k8s.io/api/apps/v1"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "k8s.io/apimachinery/pkg/util/yaml"
    "k8s.io/client-go/kubernetes"
    "k8s.io/client-go/tools/clientcmd"
    "k8s.io/client-go/util/homedir"
    "path/filepath"
)

func main() {
    var kubeconfig *string
    if home := homedir.HomeDir(); home != "" {
        kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")
    } else {
        kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
    }
    flag.Parse()
    config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
    if err != nil {
        panic(err.Error())
    }

    // create the clientset
    clientset, err := kubernetes.NewForConfig(config)
    if err != nil {
        panic(err.Error())
    }
    b, err := ioutil.ReadFile("src/yamls/nginx.yaml")
    nginxDep := &v1.Deployment{}
    nginxJson, _ := yaml.ToJSON(b)
    if err = json.Unmarshal(nginxJson, nginxDep); err != nil {
        return
    }
    if _, err = clientset.AppsV1().Deployments("zhangpeng").Create(context.Background(), nginxDep, metav1.CreateOptions{}); err != nil {
        fmt.Println(err)
        return
    }
}

go run main.go

go run main.go再运行一遍

运行第二次就报错曾经创立了,根本达到目标,其余的问题当前解决!

go文件中间接定义deployment的配置

package main

import (
    "context"
    "flag"
    "fmt"
    v1 "k8s.io/api/apps/v1"
    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"
    "k8s.io/client-go/util/homedir"
    "path/filepath"
)

func main() {
    var kubeconfig *string
    if home := homedir.HomeDir(); home != "" {
        kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")
    } else {
        kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
    }
    flag.Parse()
    config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
    if err != nil {
        panic(err.Error())
    }

    // create the clientset
    clientset, err := kubernetes.NewForConfig(config)
    if err != nil {
        panic(err.Error())
    }
    namespace := "default"
    var replicas int32 = 1
    deployment := &v1.Deployment{
        ObjectMeta: metav1.ObjectMeta{
            Name: "nginx",
            Labels: map[string]string{
                "app": "nginx",
                "env": "dev",
            },
        },
        Spec: v1.DeploymentSpec{
            Replicas: &replicas,
            Selector: &metav1.LabelSelector{
                MatchLabels: map[string]string{
                    "app": "nginx",
                    "env": "dev",
                },
            },
            Template: corev1.PodTemplateSpec{
                ObjectMeta: metav1.ObjectMeta{
                    Name: "nginx",
                    Labels: map[string]string{
                        "app": "nginx",
                        "env": "dev",
                    },
                },
                Spec: corev1.PodSpec{
                    Containers: []corev1.Container{
                        {
                            Name:  "nginx",
                            Image: "nginx:1.16.1",
                            Ports: []corev1.ContainerPort{
                                {
                                    Name:          "http",
                                    Protocol:      corev1.ProtocolTCP,
                                    ContainerPort: 80,
                                },
                            },
                        },
                    },
                },
            },
        },
    }
    deploymentList, err := clientset.AppsV1().Deployments(namespace).Create(context.TODO(), deployment, metav1.CreateOptions{})
    fmt.Println(err, deploymentList)

}


参照:https://blog.csdn.net/xujiamin0022016/article/details/123434916
以上两种形式我还是喜爱独自写yaml的形式…..

总结

  1. create就写这两个有代表性的了namespace and deployment.deployment还是很有代表性的……
  2. yaml的形式还是很不便,还是喜爱文件流的形式。
  3. 先简略搞一下crud。增删改查。而后想一下怎么整合一下一步一步来吧

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理