How to access kubernetes CRD using client-go?

Viewed 1893

I have few CRDs, but I am not exactly sure how to query kube-apiserver to get list of CRs. Can anyone please provide any sample code?

3 Answers

my sample code for an out of cluster config

    var kubeconfig *string
    kubeconfig = flag.String("kubeconfig", "./config", "(optional) relative path to the kubeconfig file")
    flag.Parse()

    // kubernetes config loaded from ./config or whatever the flag was set to
    config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
    if err != nil {
        panic(err)
    }

    // instantiate our client with config
    clientset, err := kubernetes.NewForConfig(config)
    if err != nil {
        panic(err)
    }

    // get a list of our CRs
    pl := PingerList{}
    d, err := clientset.RESTClient().Get().AbsPath("/apis/pinger.hel.lo/v1/pingers").DoRaw(context.TODO())
    if err != nil {
        panic(err)
    }
    if err := json.Unmarshal(d, &pl); err != nil {
        panic(err)
    }

PingerList{} is an object generated from Kubebuilder that I unmarshal to later in the code. However, you could just straight up println(string(d)) to get that json.

The components in the AbsPath() are "/apis/group/verison/plural version of resource name"

if you're using minikube, you can get the config file with kubectl config view

Kubernetes-related imports are the following

"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/kubernetes"

Refer this page to get information on how to access the crd using this repo

and for more information refer this document document

Either you need to use the Unstructured client, or generate a client stub. The dynamic client in the controller-runtime library is a lot nicer for this and I recommend it.

Related