您现在的位置是:首页 > 云原生 > Kubernetes > 正文
Kubernetes
使用client-go API来实现yaml文件的k8s部署
实现思路
yaml文件先转为json格式,然后json反序列化为deployment对象
实现代码
package main import ( "context" "encoding/json" "fmt" "io/ioutil" "log" v1 "k8s.io/api/apps/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" yaml2 "k8s.io/apimachinery/pkg/util/yaml" "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" ) func main() { var ( err error data []byte conf *rest.Config client *kubernetes.Clientset ) if data, err = ioutil.ReadFile("/Users/5bug/codes/projects/k8s-demo/k8s-test.yaml"); err != nil { fmt.Print(err) } if data, err = yaml2.ToJSON(data); err != nil { return } deployment := &v1.Deployment{} if err = json.Unmarshal(data, deployment); err != nil { return } cluster := deployment.ObjectMeta.ClusterName namespace := deployment.ObjectMeta.Namespace deploymentName := deployment.ObjectMeta.Name if conf, err = clientcmd.BuildConfigFromFlags("", "/Users/5bug/.kube/config"); err != nil { log.Println("BuildConfigFromFlags", err) return } if client, err = kubernetes.NewForConfig(conf); err != nil { log.Println("NewForConfig", err) return } if deployment, err = client.AppsV1().Deployments(namespace).Create(context.TODO(), deployment, metav1.CreateOptions{}); err != nil { return } fmt.Println(cluster, namespace, deploymentName) fmt.Println(deployment) return }
上面代码的功能等同于:
kubectl apply -f k8s-test.yaml
相关文章
- 在Kubernetes里使用openkruise实现服务原地升级功能
- 吾八哥学k8s(十一):kubernetes里Pod的调度机制
- 吾八哥学k8s(十):kubernetes里Service和Ingress
- kubernetes中服务自定义Prometheus的metrics的方法
- k8s集群安装Prometheus监控以及Grafana面板的方法
- kubernetes集群证书过期的解决方法
- kubelet启动失败报failed to find cgroups of kubelet的解决方法
- 吾八哥学k8s(九):kubernetes里持久化存储
- macOs和Linux环境下kubectl命令自动补齐的方法
- 吾八哥学k8s(八):kubernetes里Secret的用法