golang简易实现 k8s 的yaml上传并应用示例方案
作者:锅包肉
这篇文章主要为大家介绍了golang简易实现 k8s 的yaml上传并应用示例方案,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
plan A:调用 os模块
调用 os模块 system的 kubectl apply -f xx.yaml
package main import ( "bytes" "io/ioutil" "net/http" "os" "os/exec" _ "path/filepath" "github.com/gin-gonic/gin" _ "gopkg.in/yaml.v3" "gorm.io/driver/mysql" "gorm.io/gorm" ) type YAML struct { Content string `gorm:"type:text"` } func main() { // 初始化数据库 dsn := "root:xixu@tcp(10.23.18x.x1:3306)/texxt?charset=utf8mb4&parseTime=True&loc=Local" db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{}) if err != nil { panic(any("Failed to connect database")) } db.AutoMigrate(&YAML{}) // 初始化 Gin 路由 r := gin.Default() r.LoadHTMLGlob("./temp/*") r.GET("/upload", func(c *gin.Context) { c.HTML(http.StatusOK, "upload.html", gin.H{ "mess": "mess", }) }) r.POST("/upload", func(c *gin.Context) { // 从 HTTP 请求中读取 YAML 文件内容 file, err := c.FormFile("yaml") if err != nil { c.String(http.StatusBadRequest, "Bad request") return } f, err := file.Open() if err != nil { c.String(http.StatusBadRequest, "Bad request") return } defer f.Close() content, err := ioutil.ReadAll(f) if err != nil { c.String(http.StatusBadRequest, "Bad request") return } // 将 YAML 文件内容存储到数据库中 yaml := YAML{Content: string(content)} db.Create(&yaml) // 应用 YAML 文件内容到 Kubernetes 集群中 cmd := exec.Command("kubectl", "apply", "-f", "-") cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr cmd.Stdin = bytes.NewBufferString(yaml.Content) err = cmd.Run() if err != nil { c.String(http.StatusInternalServerError, "Internal server error") return } c.String(http.StatusOK, "YAML file uploaded successfully") }) r.Run(":8080") }
<!DOCTYPE html> <html lang="zh-CN"> <head> <title>上传文件示例</title> </head> <body> <form action="/upload" method="post" enctype="multipart/form-data"> <input type="file" name="yaml"> <input type="submit" value="上传"> </form> </body> </html>
plan B:dynamic.NewForConfig 函数创建 Kubernetes 客户端对象
我们使用 dynamic.NewForConfig 函数创建 Kubernetes 客户端对象。然后,我们读取 YAML 文件并将其转换为 Unstructured 对象。最后,我们使用 dynamic.Resource 函数来获取对应于 YAML 文件中资源类型的 Kubernetes 资源客户端,并使用 Create 或 Update 方法将资源对象应用到 Kubernetes 中
package main import ( "bytes" "context" "fmt" "io/ioutil" "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/serializer/yaml" yamlutil "k8s.io/apimachinery/pkg/util/yaml" "k8s.io/client-go/dynamic" "k8s.io/client-go/kubernetes" "k8s.io/client-go/restmapper" "k8s.io/client-go/tools/clientcmd" "log" "net/http" "os/user" _ "path/filepath" "github.com/gin-gonic/gin" _ "gopkg.in/yaml.v3" "gorm.io/driver/mysql" "gorm.io/gorm" ) type YAML1 struct { Content string `gorm:"type:text"` } func main() { // 初始化数据库 dsn := "root:xiaoxhu@tcp(10.2x.1x.1x:330x)/txst?charset=utf8mb4&parseTime=True&loc=Local" db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{}) if err != nil { panic(any("Failed to connect database")) } db.AutoMigrate(&YAML1{}) // 初始化 Gin 路由 r := gin.Default() r.LoadHTMLGlob("./temp/*") r.GET("/upload", func(c *gin.Context) { c.HTML(http.StatusOK, "upload.html", gin.H{ "mess": "mess", }) }) r.POST("/upload", func(c *gin.Context) { // 从 HTTP 请求中读取 YAML 文件内容 file, err := c.FormFile("yaml") if err != nil { c.String(http.StatusBadRequest, "Bad request") return } f, err := file.Open() if err != nil { c.String(http.StatusBadRequest, "Bad request") return } defer f.Close() content, err := ioutil.ReadAll(f) if err != nil { c.String(http.StatusBadRequest, "Bad request") return } // 将 YAML 文件内容存储到数据库中 yaml := YAML1{Content: string(content)} db.Create(&yaml) // 应用 YAML 文件内容到 Kubernetes 集群中 err = ApplyYaml(content) if err != nil { c.String(http.StatusInternalServerError, "Internal server error") return } c.String(http.StatusOK, "YAML file uploaded successfully") }) r.Run(":8080") } func ApplyYaml(filebytes []byte) error{ home := GetHomePath() nameSpace := "default" k8sConfig, err := clientcmd.BuildConfigFromFlags("", fmt.Sprintf("%s/.kube/config", home)) // 使用 kubectl 默认配置 ~/.kube/config if err != nil { fmt.Printf("%v",err) return err } // 创建一个k8s客户端 clientSet, err := kubernetes.NewForConfig(k8sConfig) if err != nil { fmt.Printf("%v",err) return err } dd, err := dynamic.NewForConfig(k8sConfig) if err != nil { log.Fatal(err) } decoder := yamlutil.NewYAMLOrJSONDecoder(bytes.NewReader(filebytes), 100) for { var rawObj runtime.RawExtension if err = decoder.Decode(&rawObj); err != nil { break } obj, gvk, err := yaml.NewDecodingSerializer(unstructured.UnstructuredJSONScheme).Decode(rawObj.Raw, nil, nil) unstructuredMap, err := runtime.DefaultUnstructuredConverter.ToUnstructured(obj) if err != nil { log.Fatal(err) } unstructuredObj := &unstructured.Unstructured{ Object: unstructuredMap} gr, err := restmapper.GetAPIGroupResources(clientSet.Discovery()) if err != nil { log.Fatal(err) } mapper := restmapper.NewDiscoveryRESTMapper(gr) mapping, err := mapper.RESTMapping(gvk.GroupKind(), gvk.Version) if err != nil { log.Fatal(err) } var dri dynamic.ResourceInterface if mapping.Scope.Name() == meta.RESTScopeNameNamespace { if unstructuredObj.GetNamespace() == "" { unstructuredObj.SetNamespace(nameSpace) } dri = dd.Resource(mapping.Resource).Namespace(unstructuredObj.GetNamespace()) } else { dri = dd.Resource(mapping.Resource) } obj2, err := dri.Create(context.Background(), unstructuredObj, metav1.CreateOptions{ }) if err != nil { log.Fatal(err) } fmt.Printf("%s/%s created", obj2.GetKind(), obj2.GetName()) } return nil } func GetHomePath() string { u , err := user.Current() if err == nil { return u.HomeDir } return "" }
以上就是golang简易实现 k8s 的yaml上传并应用示例方案的详细内容,更多关于golang k8s上传yaml的资料请关注脚本之家其它相关文章!