client-go连接kubernetes集群-create

2022-05-04 10:58:11 浏览数 (1)

背景

client-go连接kubernetes集群-connect and list。都是查看获取list列表的。现在想用client-go创建应用该如何操作呢?

client-go连接kubernetes集群-create

创建一个namespace:

代码语言:txt复制
clientset.CoreV1().Namespaces().Create
image.pngimage.png
代码语言:txt复制
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()

}
image.pngimage.png

嗯打印在一起了 也可以加个换行符?

image.pngimage.png

创建一个deployment

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

image.pngimage.png
image.pngimage.png
image.pngimage.png

*v1.Deployment怎么处理呢?单独写一个deployment的yaml文件然后文件流读取?或者直接在go文件中定义deployment的配置?

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

生成yaml文件

代码语言:txt复制
kubectl create deployment nginx --image=nginx -o yaml --dry-run=client >nginx.yaml

nginx.yaml

代码语言:txt复制
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

image.pngimage.png

main.go

代码语言:txt复制
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

image.pngimage.png

go run main.go再运行一遍

image.pngimage.png

运行第二次就报错已经创建了,基本达到目标,其他的问题以后处理!

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

代码语言:txt复制
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)

}
image.pngimage.png

参照:https://blog.csdn.net/xujiamin0022016/article/details/123434916

以上两种方式我还是喜欢单独写yaml的方式.....

总结

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

0 人点赞