How to list Pods events based on Pod Labels in kubernetes client-go

472 Views Asked by At

I want to fetch the pod events by using the Pod label in Kubernetes client-go,

I had tried the below code but not working by passing the namepsace nd podname ,

namespace := "test"
podNameInital := "testpods"
labelSelector := metav1.LabelSelector{MatchLabels: map[string]string{"test/label": "devtest1"}}
fieldSelector := fmt.Sprintf("involvedObject.name=%s", podNameInital) 
events1, _ := clientset.CoreV1().Events(namespace).List(context.TODO(), metav1.ListOptions{
        FieldSelector: fieldSelector,
         TypeMeta:      metav1.TypeMeta{Kind: "Pod"},
    })

for _, item := range events1.Items {
    fmt.Println(item)
}

please help me to fix this.

Can You help me to get the pod events only with the help of the label name? actually, I will be having only a label name, so need to get the matching pod with this label and then need to get the events from that.

1

There are 1 best solutions below

3
DazWilkin On

I think you can't because Events don't include Pod labels.

In your example, you should receive an EventList containing events where metav1.TypeMeta{Kind: "Pod"} and involvedObject.name=testpods in namespace test but, note that the events don't include the Pod labels.

You can prove this to yourself by enumerating the EventList without the labelSelector:

fieldSelector := fmt.Sprintf("involvedObject.name=%s", podNameInital)
events, _ := clientset.CoreV1().Events(namespace).List(
    context.TODO(),
    metav1.ListOptions{
        FieldSelector: fieldSelector,
        TypeMeta:      metav1.TypeMeta{Kind: "Pod"},
    },
)

log.Printf("%d events", len(events.Items))
b, err := json.MarshalIndent(events, "", "  ")
if err != nil {
    log.Println("unable to marshal Events")
}

log.Println(string(b))