未知yaml中gvk时候client go创建资源
2022-07-25 本文已影响0人
wwq2020
package main
import (
"context"
"io/ioutil"
"k8s.io/client-go/rest"
"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"
yamlCodec "k8s.io/apimachinery/pkg/runtime/serializer/yaml"
"k8s.io/client-go/discovery"
memory "k8s.io/client-go/discovery/cached"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/restmapper"
)
func dynamicCreate(ctx context.Context, cfg *rest.Config, codec runtime.Serializer, data []byte) error {
discoveryClient, err := discovery.NewDiscoveryClientForConfig(cfg)
if err != nil {
return err
}
mapper := restmapper.NewDeferredDiscoveryRESTMapper(memory.NewMemCacheClient(discoveryClient))
dynamicClient, err := dynamic.NewForConfig(cfg)
if err != nil {
return err
}
obj := &unstructured.Unstructured{}
_, gvk, err := codec.Decode(data, nil, obj)
if err != nil {
return err
}
mapping, err := mapper.RESTMapping(gvk.GroupKind(), gvk.Version)
if err != nil {
return err
}
var dynamicResource dynamic.ResourceInterface = dynamicClient.Resource(mapping.Resource)
if mapping.Scope.Name() == meta.RESTScopeNameNamespace {
namesapce := obj.GetNamespace()
if namesapce == "" {
namesapce = "default"
}
dynamicResource = dynamicClient.Resource(mapping.Resource).Namespace(namesapce)
}
if _, err := dynamicResource.Create(ctx, obj, metav1.CreateOptions{}); err != nil {
return err
}
return nil
}
func main() {
data, err := ioutil.ReadFile("./demo.yaml")
if err != nil {
panic(err)
}
restConfig := &rest.Config{
Host: "yourk8shost",
BearerToken: "yourtoken",
TLSClientConfig: rest.TLSClientConfig{
Insecure: true,
},
}
ctx := context.TODO()
codec := yamlCodec.NewDecodingSerializer(unstructured.UnstructuredJSONScheme)
if err := dynamicCreate(ctx, restConfig, codec, data); err != nil {
panic(err)
}
}