• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

client-go开发k8s:创建deployment

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

简介、创建deployment有多种方式,如引用创建编排好的yaml文件,然后直接创建,或者在代码内写好需要的文件再进行创建,本文将都举例进行

1、引用本地的yaml文件进行创建,并且更新replicas

package main

import (
	"context"
	"encoding/json"
	"flag"
	"fmt"
	"io/ioutil"
	"path/filepath"

	v1 "k8s.io/api/apps/v1"
	"k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	yaml "k8s.io/apimachinery/pkg/util/yaml"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/clientcmd"
	"k8s.io/client-go/util/homedir"
)

func main() {
	// create the clientset
	clientset := K8sClient()
	var (
		err    error
		data   []byte
		deployment =&v1.Deployment{}
		replicas int32
	)
	//读取yaml
	if data, err = ioutil.ReadFile("C:/Users/72088854/go/src/config"); err != nil {
		fmt.Print(err)
	}
	//yaml转json
	if data, err = yaml.ToJSON(data); err != nil {
		return
	}
	//json转struct
	if err = json.Unmarshal(data, deployment); err != nil {
		return
	}

	deploymentName := deployment.ObjectMeta.Name

	//定义副本的数量
	replicas = 4
	deployment.Spec.Replicas = &replicas

	fmt.Println(deploymentName)
	if _, err = clientset.AppsV1().Deployments("default").Get(context.TODO(),deploymentName, metav1.GetOptions{}); err !=nil {
		if !errors.IsNotFound(err) {
			fmt.Println(err)
			return
		}
		//如果不存在则创建deployment
		if _, err = clientset.AppsV1().Deployments("default").Create(context.TODO(), deployment, metav1.CreateOptions{}); err != nil {
			fmt.Println(err)
			return
		}

	} else {
		//如果存在则更新deployement
		if _, err = clientset.AppsV1().Deployments("default").Update(context.TODO(), deployment,metav1.UpdateOptions{}); err != nil {
			fmt.Println(err)
			return
		}
	}
	fmt.Println("create成功!!!")

}

2、代码内书写yaml进行创建

package main

import (
	"context"
	"flag"
	"fmt"
	"path/filepath"

	v1 "k8s.io/api/apps/v1"
	apiv1 "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"
)

func main() {
	// create the clientset
	clientset := K8sClient()
	var (
		err    error
		deploys =&v1.Deployment{}
	)

	//json转struct
	deployment := &v1.Deployment{
		ObjectMeta: metav1.ObjectMeta{
			Name: "vc-web",
		},
		Spec: v1.DeploymentSpec{
			Replicas: int32Ptr(2),
			Selector: &metav1.LabelSelector{
				MatchLabels: map[string]string{
					"app": "vc-web",
				},
			},
			Template: apiv1.PodTemplateSpec{
				ObjectMeta: metav1.ObjectMeta{
					Labels: map[string]string{
						"app": "vc-web",
						"version": "V1",
					},
				},
				Spec: apiv1.PodSpec{
					Containers: []apiv1.Container{
						{
							Name: "vc-web",
							Image: "nginx:1.13.5-alpine",
							ImagePullPolicy: "IfNotPresent",
							Ports: []apiv1.ContainerPort{
								{
									Name: "http",
									Protocol: apiv1.ProtocolTCP,
									ContainerPort: 80,
								},
							},
						},
					},
				},

			},
		},

	}
	cluster := deployment.ObjectMeta.ClusterName
	namespace := deployment.ObjectMeta.Namespace

	deploymentName := deployment.ObjectMeta.Name
	fmt.Println("hello",deploymentName)
	if deployment, err = clientset.AppsV1().Deployments(apiv1.NamespaceDefault).Create(context.TODO(), deployment, metav1.CreateOptions{}); err != nil {
		fmt.Println(err.Error())
		return
	}

	fmt.Println("create成功!!!")
	fmt.Println(cluster, namespace, deploymentName)

}

func int32Ptr(i int32) *int32 {
	return &i
}

func K8sClient() *kubernetes.Clientset {
	// 使用当前上下文环境
	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())
	}
	// 根据指定的 config 创建一个新的 clientSet
	clientSet, err := kubernetes.NewForConfig(config)
	if err != nil {
		panic(err.Error())
	}
	return clientSet
}

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap