运行 :

1: 在k8s 机器运行

2: 拷贝 K8S 配置文件到本机

3: 指定config文件

坑:

1:注意K8S版本,我的版本是1.18.5 ,以下文件版本号自行到github匹配

2:可能会报 K8S-context 找不到、

运行截图:

 

go.mod 

module kube-demo

go 1.16

require (
	k8s.io/api v0.20.0
	k8s.io/apimachinery v0.20.0
	k8s.io/client-go v0.20.0
)

代码段:

package main

import (
	"context"
	"flag"
	"fmt"
	appv1 "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"
	"path/filepath"
	"time"
)

type k8sClient struct {
	k8s *kubernetes.Clientset
}

var kubeconfig *string

func init() {
	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")
	}
}

func newK8s() (*k8sClient, error) {
	config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
	if err != nil {
		fmt.Println("#1 fail to init client:", err)
		return nil, err
	}
	c, err := kubernetes.NewForConfig(config)
	if err != nil {
		fmt.Println("#2 fail to init client:", err)
		return nil, err
	}
	fmt.Println("connect kubernetes cluster success.")
	return &k8sClient{
		c,
	}, nil
}

func (c *k8sClient) nsCreate(nsName string) {
	ctx := context.Background()
	nsClient := c.k8s.CoreV1().Namespaces()
	ns := &apiv1.Namespace{
		ObjectMeta: metav1.ObjectMeta{
			Name: nsName,
		},
		Status: apiv1.NamespaceStatus{
			Phase: apiv1.NamespaceActive,
		},
	}
	opt := metav1.CreateOptions{}
	ns, err := nsClient.Create(ctx, ns, opt)
	if err != nil {
		panic(err)
	}
}

func (c *k8sClient) nsList() {
	ctx := context.Background()
	ns, err := c.k8s.CoreV1().Namespaces().List(ctx, metav1.ListOptions{})
	if err != nil {
		panic(err)
	}
	// 循环打印pod的信息
	for _, pod := range ns.Items {
		fmt.Println("ns :", pod.Name)
	}
}

func (c *k8sClient) depList() {
	ctx := context.Background()
	dep, err := c.k8s.AppsV1().Deployments("default").List(ctx, metav1.ListOptions{})
	if err != nil {
		return
	}
	for _, svc := range dep.Items {
		fmt.Println("Deployments:  name:", svc.Name, "Replicas:", *svc.Spec.Replicas)
	}
}

func (c *k8sClient) podList() {
	ctx := context.Background()
	pod, err := c.k8s.CoreV1().Pods("default").List(ctx, metav1.ListOptions{})
	if err != nil {
		return
	}
	for _, p := range pod.Items {
		for i := 0; i < len(p.Spec.Containers); i++ {
			//c := p.Spec.Containers[i]
			//fmt.Println("pods:",p.UID, p.Name, c.Image, c.Ports, p.Annotations["cni.projectcalico.org/podIP"])
			fmt.Println("pods:",p.UID, p.Name,  p.Annotations["cni.projectcalico.org/podIP"])
		}
	}
}

func (c *k8sClient) svcList() {
	ctx := context.Background()
	svclist, err := c.k8s.CoreV1().Services("default").List(ctx, metav1.ListOptions{})
	if err != nil {
		return
	}
	for _, svc := range svclist.Items {
		fmt.Println("svc:",svc.Name, svc.Spec.ClusterIP, svc.Spec.Ports)
	}
}

func (c *k8sClient) deploymentCreate(ns string) {
	repl := int32(1)                 // 副本数量
	match := make(map[string]string) // 标签选择器
	match["app"] = "nginx"
	var podSpec = apiv1.Container{
		Name:            "golang-client",
		Image:           "redis",
		ImagePullPolicy: "IfNotPresent",
	}
	containers := []apiv1.Container{podSpec}

	var templateSpec = apiv1.PodTemplateSpec{
		ObjectMeta: metav1.ObjectMeta{
			Name:   "testpod",
			Labels: match,
		},
		Spec: apiv1.PodSpec{
			Containers: containers,
		},
	}

	selecter := metav1.LabelSelector{
		MatchLabels: match,
	}
	deploy := appv1.Deployment{
		ObjectMeta: metav1.ObjectMeta{
			Name: ns,
		},
		Spec: appv1.DeploymentSpec{
			Replicas: &repl,
			Selector: &selecter,
			Template: templateSpec,
		},
	}
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*2)
	defer cancel()
	var opt = metav1.CreateOptions{}
	podsClient, err := c.k8s.AppsV1().Deployments(ns).Create(ctx, &deploy, opt)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	fmt.Printf("%#v\n", podsClient)
}

func (c *k8sClient) svcCreate() {
	// Payload field must start with Upper Case, and Request Body must start with Lower Case
	type Payload struct {
		Project  string
		Name     string
		Labels   map[string]string
		Ports    []apiv1.ServicePort
		Selector map[string]string
		Type     apiv1.ServiceType
	}
	svcName := `demo-svc-name`
	var payload = &Payload{
		Name:     svcName,
		Labels:   map[string]string{},
		Ports:    []apiv1.ServicePort{apiv1.ServicePort{Name: "Http", Port: 8001}},
		Selector: map[string]string{"app": svcName},
		Type:     apiv1.ServiceTypeNodePort,
	}
	params := &apiv1.Service{
		ObjectMeta: metav1.ObjectMeta{
			Name:   payload.Name,
			Labels: payload.Labels,
		},
		Spec: apiv1.ServiceSpec{
			Ports:    payload.Ports,
			Selector: payload.Selector,
			Type:     payload.Type,
		},
	}
	opt := metav1.CreateOptions{}
	ctx := context.Background()
	result, err := c.k8s.CoreV1().Services(payload.Project).Create(ctx, params, opt)
	if err != nil {
		fmt.Println(err.Error())
	}
	fmt.Println(result)
}

func main() {
	flag.Parse()
	k8s, err := newK8s()
	if err != nil {
		panic(err.Error())
	}
	k8s.nsList()
	k8s.podList()
	k8s.depList()
	k8s.svcList()
}

Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐