通过调用client-go客户端使用yaml文件的方式部署服务到K8S集群内
func main() {
namespace := "test"
config, err := clientcmd.BuildConfigFromFlags("", "config")
if err != nil {
panic(err.Error())
}
client, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
dc := client.Discovery()
restMapperRes, err := restmapper.GetAPIGroupResources(dc)
if err != nil {
log.Fatal(err)
}
restMapper := restmapper.NewDiscoveryRESTMapper(restMapperRes) //
//待创建的文件
yamls := []string{"deployment.yaml", "service.yaml"}
for _, s := range yamls {
fmt.Println(s, "======")
f, err := os.Open(s)
if err != nil {
log.Fatal(err)
}
d := yaml.NewYAMLOrJSONDecoder(f, 4096)
for {
ext := runtime.RawExtension{}
if err := d.Decode(&ext); err != nil {
if err == io.EOF {
break
}
log.Fatal(err)
}
fmt.Println("raw: ", string(ext.Raw))
obj, gvk, err := unstructured.UnstructuredJSONScheme.Decode(ext.Raw, nil, nil)
fmt.Printf("gvk: %+v\n", gvk)
mapping, err := restMapper.RESTMapping(gvk.GroupKind(), gvk.Version)
fmt.Printf("mapping:%+v\n", mapping)
if err != nil {
log.Fatal(err)
}
// runtime.Object转换为unstructed
unstructuredObj, err := runtime.DefaultUnstructuredConverter.ToUnstructured(obj)
if err != nil {
log.Fatal(err)
}
fmt.Printf("unstructuredObj: %+v", unstructuredObj)
var unstruct unstructured.Unstructured
unstruct.Object = unstructuredObj
if md, ok := unstruct.Object["metadata"]; ok {
metadata := md.(map[string]interface{})
if internalns, ok := metadata["namespace"]; ok {
namespace = internalns.(string)
}
}
// 动态客户端
dclient, err := dynamic.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
res, err := dclient.Resource(mapping.Resource).Namespace(namespace).Create(context.TODO(), &unstruct, metav1.CreateOptions{})
if err != nil {
log.Fatal(err)
}
fmt.Println(res, "=============")
}
}
}
本文参考自https://blog.dianduidian.com/post/kubernetes-client-go%E5%AE%9E%E7%8E%B0yaml%E5%88%9B%E5%BB%BAdeployment/
标签:err,nil,fmt,yaml,client,go,Fatal,log From: https://www.cnblogs.com/zly-go/p/16778499.html