Created
April 19, 2023 10:38
-
-
Save squeed/37d4f10e43a194fb2eb6640f08d59b0e to your computer and use it in GitHub Desktop.
HOWTO actually use the kubernetes generic client
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"fmt" | |
"os" | |
"path" | |
corev1 "k8s.io/api/core/v1" | |
v1 "k8s.io/apimachinery/pkg/apis/meta/v1" | |
"k8s.io/apimachinery/pkg/runtime" | |
cacheddiscovery "k8s.io/client-go/discovery/cached/memory" | |
"k8s.io/client-go/dynamic" | |
"k8s.io/client-go/kubernetes" | |
"k8s.io/client-go/rest" | |
"k8s.io/client-go/restmapper" | |
"k8s.io/client-go/tools/clientcmd" | |
"k8s.io/kubectl/pkg/scheme" | |
) | |
func GetObject[T runtime.Object](cfg *rest.Config, dest T, namespace, name string) error { | |
// in reality, you would only construct these once | |
clientset, err := kubernetes.NewForConfig(cfg) | |
if err != nil { | |
return err | |
} | |
dynamicClientset, err := dynamic.NewForConfig(cfg) | |
if err != nil { | |
return err | |
} | |
discoveryClient := cacheddiscovery.NewMemCacheClient(clientset.Discovery()) | |
mapper := restmapper.NewDeferredDiscoveryRESTMapper(discoveryClient) | |
// end one-time construction | |
// Map object to GroupVersionKind | |
kinds, _, _ := scheme.Scheme.ObjectKinds(dest) | |
// But bail if the object doesn't have exactly one GVK | |
if len(kinds) != 1 { | |
return fmt.Errorf("bad kinds") | |
} | |
gvk := kinds[0] | |
// Map GVK to server resource | |
restMapping, err := mapper.RESTMapping(gvk.GroupKind(), gvk.Version) | |
if err != nil { | |
return err | |
} | |
// Finally, we can get what we were looking for | |
uns, err := dynamicClientset.Resource(restMapping.Resource).Namespace(namespace).Get(context.TODO(), name, v1.GetOptions{}) | |
if err != nil { | |
return nil | |
} | |
if err := scheme.Scheme.Convert(uns, dest, nil); err != nil { | |
return err | |
} | |
return nil | |
} | |
func main() { | |
home, err := os.UserHomeDir() | |
if err != nil { | |
panic(err) | |
} | |
// note: better to use genericclioptions + LoadingRules | |
cfg, err := clientcmd.BuildConfigFromFlags("", path.Join(home, ".kube", "config")) | |
if err != nil { | |
panic(err) | |
} | |
p := &corev1.Pod{} | |
if err := GetObject(cfg, p, "kube-system", "kube-apiserver-kind-control-plane"); err != nil { | |
panic(err) | |
} | |
fmt.Printf("%+v\n", p) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment