How to apply yaml resource using go-client? (unstructured api)

171 views Asked by At

I'm getting around with the unstructured api

client := kubernetes.NewForConfig(rest.InClusterConfig())
groupResourceVersion := schema.GroupVersionResource{
        Group:    unstruct.GetObjectKind().GroupVersionKind().Group,
        Version:  unstruct.GetObjectKind().GroupVersionKind().Version,
        Resource: unstruct.GetObjectKind().GroupVersionKind().Kind, // Resource == Kind ??
}
client.Resource(groupResourceVersion).Create(
        ctx,
        unstruct,
        metav1.CreateOptions{},
)

How do you map a GroupVersionKind to GroupVersionResource?

1

There are 1 answers

0
Juancki On

Answering my own question, it seems that a REST call using restmapper is needed:

func getGroupVersionResource(gvk schema.GroupVersionKind) (schema.GroupVersionResource, error) {
    clientSet, err := kubernetes.NewForConfig(clusterConfig)
    if err != nil {
        return schema.GroupVersionResource{}, err
    }
    // Create a REST mapper that tracks information about the available resources in the cluster.
    groupResources, err := restmapper.GetAPIGroupResources(clientSet.Discovery())
    if err != nil {
        return schema.GroupVersionResource{}, err
    }
    rm := restmapper.NewDiscoveryRESTMapper(groupResources)

    gk := schema.GroupKind{Group: gvk.Group, Kind: gvk.Kind}
    mapping, err := rm.RESTMapping(gk, gvk.Version)
    if err != nil {
        return schema.GroupVersionResource{}, err
    }
    return mapping.Resource, nil
}