AlexS
AlexS

Reputation: 917

kubernetes filter objects in Informer

Im writing custom controller for kubernetes. Im creating shared informer

cache.NewSharedIndexInformer(
            &cache.ListWatch{
                ListFunc: func(options meta_v1.ListOptions) (k8sruntime.Object, error) {

                    return client.CoreV1().ConfigMaps(nameSpace).List(options)
                },
                WatchFunc: func(options meta_v1.ListOptions) (watch.Interface, error) {

                    return client.CoreV1().ConfigMaps(nameSpace).Watch(options)
                },
            },
            &api_v1.ConfigMap{},
            0, //Skip resyncr
            cache.Indexers{},
        )

I have option to add filtering function into call back functions to further decrease number of objects im working with. Something like that

options.FieldSelector := fields.OneTermEqualSelector("metadata.name", nodeName).String()

I would like to filter out objects by regular expression. Or by some label at least. Unfortunately documentation is not helping. Could not find anything except for tests for code itself. Ho do i apply regular expression on filtering mechanism? Where do i get some examples on this issue?

Upvotes: 2

Views: 4975

Answers (1)

AlexS
AlexS

Reputation: 917

Its not possible to filter objects by regular expression. It is possible to filer object by lable

This is the code that will filter by label

labelSelector := labels.Set(map[string]string{"mylabel": "ourdaomain1"}).AsSelector()

informer := cache.NewSharedIndexInformer(
    &cache.ListWatch{
        ListFunc: func(options meta_v1.ListOptions) (k8sruntime.Object, error) {

            options.LabelSelector = labelSelector.String()
            return client.CoreV1().ConfigMaps(nameSpace).List(options)
        },
        WatchFunc: func(options meta_v1.ListOptions) (watch.Interface, error) {

            options.LabelSelector = labelSelector.String()
            return client.CoreV1().ConfigMaps(nameSpace).Watch(options)
        },
    },
    &api_v1.ConfigMap{},
    0, //Skip resyncr
    cache.Indexers{},
)

Another thing that is important to remember is how do you add new objects to k8s I was doing something like

kubectl --namespace==ourdomain1 create configmap config4 -f ./config1.yaml

This is not good. It overwrites all the fields in config map and puts whole file content into data of the new object. Proper way is

kubectl create  -f ./config1.yam

Upvotes: 4

Related Questions