5

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?

  • Any news? I read that kubebuilder can be used for this. But I cannot understand, If I need just to get status of the CR, why I need to generate whole new api resource. I just want to expose some metrics about CRDs for prometheus( – DeamonMV May 18 '21 at 13:39
  • where is the code running? in the cluster or out of the cluster? [Here](https://github.com/kubernetes/client-go/tree/master/examples) are examples from the client-go repo. – Galletti_Lance Dec 09 '21 at 21:58

3 Answers3

2

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"
Donovan Jenkins
  • 133
  • 1
  • 13
0

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

and for more information refer this document document

  • 2
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/29981440) – eglease Oct 04 '21 at 06:19
  • 1
    Ok will keep that in mind and will edit the answer too – achudiwal45 Oct 05 '21 at 08:01
-3

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.

coderanger
  • 52,400
  • 4
  • 52
  • 75