Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to list all kubernetes objects with specific label using client-go

I want to execute equivalent of

kubectl get all -l app=myapp -n mynamespace

or

kubectl label all -l version=1.2.0,app=myapp track=stable --overwrite

using client-go

I looked at dynamic package, but it seems like it needs GroupVersionResource, which is different for, say, Service objects and Deployment objects. Also when I pass schema.GroupVersionResource{Group: "apps", Version: "v1"} it doesn't find anything, when I pass schema.GroupVersionResource{Version: "v1"} it finds only namespace object and also doesn't looks for labels, though I provided label options:

resource := schema.GroupVersionResource{Version: "v1"}
listOptions := metav1.ListOptions{LabelSelector: fmt.Sprintf("app=%s", AppName), FieldSelector: ""}
res, listErr := dynamicClient.Resource(resource).Namespace("myapps").List(listOptions)

I also looked at runtime package, but didn't find anything useful. I took a look at how kubectl implement this, bit haven't figured it out yet, too many levels of abstractions.

like image 276
Kseniia Churiumova Avatar asked Feb 13 '19 16:02

Kseniia Churiumova


1 Answers

You can't list "all objects" with one call.

Unfortunately the way Kubernetes API is architected is via API groups, which have multiple APIs under them.

So you need to:

  1. Query all API groups (apiGroup)
  2. Visit each API group to see what APIs (kind) it exposes.
  3. Actually query that kind to get all the objects (here you may actually filter the list query with the label).

Fortunately, kubectl api-versions and kubectl api-resources commands do these.

So to learn how kubectl finds all "kinds" of API resources, run:

kubectl api-resources -v=6

and you'll see kubectl making calls like:

  • GET https://IP/api
  • GET https://IP/apis
  • then it visits every api group:
    • GET https://IP/apis/metrics.k8s.io/v1beta1
    • GET https://IP/apis/storage.k8s.io/v1
    • ...

So if you're trying to clone this behavior with client-go, you should use the same API calls, or better just write a script just shells out to kubectl api-resources -o=json and script around it.

like image 147
ahmet alp balkan Avatar answered Oct 12 '22 23:10

ahmet alp balkan