kubernetes 工具开发

简介与目的

我们在使用k8s 过程中,有时候需要对集群进行管理、统计、服务发现等等。这时需要依赖k8s 的客户端sdk进行开发。

依赖的包

metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/pkg/api/v1"

"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"

创建Clientset

var clientset *kubernetes.Clientset
if *inCluster {
	var err error
	// creates the in-cluster config 集群内部配置
	config, err := rest.InClusterConfig()
	if err != nil {
		panic(err.Error())
	}
	// creates the clientset
	clientset, err = kubernetes.NewForConfig(config)
	if err != nil {
		panic(err.Error())
	}
} else {
	var err error
	// uses the current context in kubeconfig 集群外部配置,使用kubeconfig 配置文件进行连接
	config, err := clientcmd.BuildConfigFromFlags("", *kubeConfig)
	if err != nil {
		panic(err.Error())
	}
	// creates the clientset
	clientset, err = kubernetes.NewForConfig(config)
	if err != nil {
		panic(err.Error())
	}
}

这个clientset 分为集群内以及集群外。集群内可以使用service account 进行授权

示例

获取pods

clientset.CoreV1().Pods("").List(metav1.ListOptions{})

创建deployment

deploymentsClient := clientset.AppsV1beta1().Deployments(apiv1.NamespaceDefault)

deployment := &appsv1beta1.Deployment{
	ObjectMeta: metav1.ObjectMeta{
		Name: "demo-deployment",
	},
	Spec: appsv1beta1.DeploymentSpec{
		Replicas: int32Ptr(2),
		Template: apiv1.PodTemplateSpec{
			ObjectMeta: metav1.ObjectMeta{
				Labels: map[string]string{
					"app": "demo",
				},
			},
			Spec: apiv1.PodSpec{
				Containers: []apiv1.Container{
					{
						Name:  "web",
						Image: "nginx:1.12",
						Ports: []apiv1.ContainerPort{
							{
								Name:          "http",
								Protocol:      apiv1.ProtocolTCP,
								ContainerPort: 80,
							},
						},
					},
				},
			},
		},
	},
}

更多示例可参考 k8s-client-go

humboldt Written by:

humboldt 的趣味程序园