package main
import (
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/kubernetes"
appsv1 "k8s.io/api/apps/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
apiv1 "k8s.io/api/core/v1"
"k8s.io/client-go/kubernetes/typed/apps/v1"
"flag"
"fmt"
"encoding/json"
)
func main() {
//kubelet.kubeconfig 是文件对应地址
kubeconfig := flag.String("kubeconfig", "/root/.kube/config", "(optional) absolute path to the kubeconfig file")
flag.Parse()
// 解析到config
config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
if err != nil {
panic(err.Error())
}
// 创建连接
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
deploymentsClient := clientset.AppsV1().Deployments("default")
//创建deployment
createDeployment(deploymentsClient)
//监听deployment
startWatchDeployment(deploymentsClient)
}
//监听Deployment变化
func startWatchDeployment(deploymentsClient v1.DeploymentInterface) {
w, _ := deploymentsClient.Watch(metav1.ListOptions{})
for {
select {
case e, _ := <-w.ResultChan():
fmt.Println(e.Type, e.Object)
}
}
}
//创建deployemnt,需要谨慎按照部署的k8s版本来使用api接口
func createDeployment(deploymentsClient v1.DeploymentInterface) {
var r apiv1.ResourceRequirements
//r = new(*apiv1.ResourceRequirements)
//资源分配会遇到无法设置值的问题,故采用json反解析
j := `{"limits": {"cpu":"200m", "memory": "1Gi"}, "requests": {"cpu":"200m", "memory": "1Gi"}}`
json.Unmarshal([]byte(j), &r)
deployment := &appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{
Name: "nginx",
Labels: map[string]string{
"app": "nginx",
},
},
Spec: appsv1.DeploymentSpec{
Replicas: int32Ptr2(1),
Selector: &metav1.LabelSelector{
MatchLabels: map[string]string{
"app": "nginx",
},
},
Template: apiv1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
"app": "nginx",
},
},
Spec: apiv1.PodSpec{
Containers: []apiv1.Container{
{ Name: "nginx",
Image: "nginx:1.13.5-alpine",
Resources: r,
ImagePullPolicy: "IfNotPresent",
Ports: []apiv1.ContainerPort{
{
Name: "http",
Protocol: apiv1.ProtocolTCP,
ContainerPort: 80,
},
},
},
},
},
},
},
}
fmt.Println("Creating deployment...")
result, err := deploymentsClient.Create(deployment)
if err != nil {
panic(err)
}
fmt.Printf("Created deployment %s.\n", result.GetObjectMeta().GetName())
}
func int32Ptr2(i int32) *int32 { return &i }