Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kubernetes client-go: convert labelselector to label string

In the kubernetes client-go API (or another library that uses it), is there a utility function to convert a k8s.io/apimachinery/pkg/apis/meta/v1/LabelSelector to a string to fill the field LabelSelector in k8s.io/apimachinery/pkg/apis/meta/v1/ListOptions?

I digged through the code of client-go but I can't find a function like that.

The LabelSelector.Marshall() nor LabelSelector.String() give me that (unsurprisingly, because that's not their purpose, but I tried it anyway).

Background

I have spec descriptions like k8s.io/api/extensions/v1beta1/Deployment, and want to use it's set of selector labels (i.e. the Selector field) to query it's pods using

options := metav1.ListOptions{
    LabelSelector: <stringified labels>,
}

podList, err := clientset.CoreV1().Pods(<namespace>).List(options)
like image 257
bobbel Avatar asked May 21 '19 04:05

bobbel


People also ask

How do I change labels on Kubernetes?

You can change the labels on individual pods using the kubectl label command, documented here. Changing the label of a running pod should not cause it to be restarted, and services will automatically detect and handle label changes. Save this answer.

How do I label a pod list?

To list the pods with label key “owner” and value “ahmad”, we will use the --selector option. Next, use the short option -l to select the pod with label env=develop. Kubernetes labels are not only for pods. You can apply them to all sorts of objects, including nodes, services, and deployments.

What is the difference between labels and selectors in Kubernetes?

Labels are properties that we can attach to each item for example for their type, kind, and so on. Selectors help us in finding these items. You can think of a selector as a filter. We could label pods based on some attributes i.e. app name, front-end, back-end.


1 Answers

You can use LabelSelectorAsMap(LabelSelector) function to convert the labelselector into map[string]string map.

Then, use SelectorFromSet function of package k8s.io/apimachinery/pkg/labels to convert map to selector/strings.

Pseudo code:

import (
    "k8s.io/apimachinery/pkg/labels"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

func ListPod(labelSelector metav1.LabelSelector) {

    labelMap := metav1.LabelSelectorAsMap(labelSelector)

    options := metav1.ListOptions{
        LabelSelector: labels.SelectorFromSet(labelMap).String(),
    }

    podList, err := clientset.CoreV1().Pods("<namespace>").List(options)

}
like image 189
Abdullah Al Maruf - Tuhin Avatar answered Nov 15 '22 07:11

Abdullah Al Maruf - Tuhin