Get annotations from object in k8s event handler

Viewed 475

I'm building a little k8s controller based on the sample-controller.

I'm listening for ServiceAccount events with the following event handler:

...
serviceAccountInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
    AddFunc:    controller.enqueueServiceAccount,
    DeleteFunc: controller.enqueueServiceAccount,
})
...

func (c *Controller) enqueueServiceAccount(obj interface{}) {
    var key string
    var err error

    if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil {
        utilruntime.HandleError(err)
        return
    }
    c.workqueue.Add(key)
}

This is working fine; my events are coming in and the enqueueServiceAccount() function is getting called.

This is my first foray into Golang and I can't figure out how to get the object's Kubernetes annotations from the obj.

I dumped the object with go-spew and can confirm it's got an ObjectMeta. I'm just not sure how I cast this into some object where I can access the ObjectMeta - and from there it should be easy to get the annotations (in this case this object does't have any, it's one of the <nil> values.

(*v1.ServiceAccount)(0xc0002c1010)(&ServiceAccount{ObjectMeta:{kube-proxy  kube-system /api/v1/namespaces/kube-system/serviceaccounts/kube-proxy d2013421-92c8-44ae-b6d8-202231ea557c 234 0 2021-04-29 18:40:20 +0100 BST <nil> <nil> map[eks.amazonaws.com/component:kube-proxy k8s-app:kube-proxy] map[kubectl.kubernetes.io/last-applied-configuration:{"apiVersion":"v1","kind":"ServiceAccount","metadata":{"annotations":{},"labels":{"eks.amazonaws.com/component":"kube-proxy","k8s-app":"kube-proxy"},"name":"kube-proxy","namespace":"kube-system"}}

How can I access this object's annotations?

2 Answers

You can use a MetaAccessor:

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

var metaAccessor = metav1.NewAccessor()

func (c *Controller) enqueueServiceAccount(obj interface{}) {
    if typed, ok := obj.(runtime.Object); ok {
        annotations, err := metaAccessor.Annotations(typed)
    }
}

But often people tend to use controller-runtime.

SampleController is not the most easy code to deal with. They have example on how they cast objects to a known resource type. And they also have example on how they lookup the resource from a lister.

Unless you have specific needs, I would recommend to also consider using kubebuilder and follow the kubebuilder book that has intuitive explanations of making controllers.

Related