DEV Community

Cover image for K8s Operator - Index with name ... does not exist
Maxime Guilbert
Maxime Guilbert

Posted on

K8s Operator - Index with name ... does not exist

During development on a Kubernetes operators, you may have this error while trying to get a list of objects filtering by a specific field.

can not retrieve list of objects using index : Index with name [field path] does not exist
Enter fullscreen mode Exit fullscreen mode

What generates this issue?

From what I've seen, by default only fields which are constantly defined are indexed. (like mandatory fields in your spec)

So if you try to filter on another field, there are high chances that you will have the error.


How to resolve this issue?

To resolve this issue, you can declare a new index to your manager instance and your context.

You will need :

  • the kind of object which will have the new index
  • the name of the new index (generally corresponding to the path to the desired field)
  • the function which will return the value associated to the index

Example

package main

import (
    "context"

    k8sruntime "k8s.io/apimachinery/pkg/runtime"
    "example.com/example-operator/pkg/apis/example/v1alpha1"  
    "sigs.k8s.io/controller-runtime/pkg/client"
    // ...
)

function main() {
    // ...

    cache := mgr.GetCache()

    indexFunc := func(obj client.Object) []string {
        return []string{obj.(*v1alpha1.Example).Spec.SomeField}
    }

    if err := cache.IndexField(ctx, &v1alpha1.Example{}, "spec.someField", indexFunc); err != nil {
        panic(err)
    }

    // ...
}
Enter fullscreen mode Exit fullscreen mode

As a result, even if it is generally used to index another field from an objecct, you can create an index which will return a dynamic value. Something which can be really useful in a lot of cases. (ex: Return true if the object contains some specific value in multiple fields)


I hope it will help you and if you have any questions (there are not dumb questions) or some points are not clear for you, don't hesitate to add your question in the comments or to contact me directly on LinkedIn.


You want to support me?

Buy Me A Coffee

Top comments (0)