美文网首页
gvk和gvr简单介绍

gvk和gvr简单介绍

作者: wwq2020 | 来源:发表于2023-12-14 11:36 被阅读0次

    简介

    gvk用于yaml中.对应资源对象(比如pod)

    gvr用于url中,对应资源crud等的api

    比如我们kubectl create -f xx.yaml时

    读取yaml,得到gvk
    discovery client访问apiserver得到restmapper
    通过restmapper难道gvk对应的gvr
    根据gvr拼接url
    对指定url发送对应的yaml内容
    

    可以通过kubectl get --raw='/api'或者kubectl get --raw='/apis'查看有哪些gv

    如可以通过kubectl get --raw='/api/v1' 查看有哪些gvr以及gvr对应的kind

    示例

    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"
        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 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)
    
        discoveryClient, err := discovery.NewDiscoveryClientForConfig(restConfig)
        if err != nil {
            panic(err)
        }
    
        mapper := restmapper.NewDeferredDiscoveryRESTMapper(memory.NewMemCacheClient(discoveryClient))
        dynamicClient, err := dynamic.NewForConfig(restConfig)
        if err != nil {
            panic(err)
        }
    
        obj := &unstructured.Unstructured{}
        _, gvk, err := codec.Decode(data, nil, obj)
        if err != nil {
            panic(err)
        }
    
        mapping, err := mapper.RESTMapping(gvk.GroupKind(), gvk.Version)
        if err != nil {
            panic(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 {
            panic(err)
        }
    }
    
    

    相关文章

      网友评论

          本文标题:gvk和gvr简单介绍

          本文链接:https://www.haomeiwen.com/subject/nvoigdtx.html