Filter Kubernetes events by deployment name or label selector

3/7/2020

When running kubectl get events, is there a way to filter by events without knowing the name of the pod?

I am trying to do this with Azure Pipeline's Kubectl task, which is limited to passing arguments to kubectl get events, but does not allow subshells and pipes, so grep and awk are not available.

I tried using kubectl get events --field-selector involvedObject.name=my-microservice-name, which works to an extent (i.e., for the deployment resource), but not for the pods.

Using kubectl get events --field-selector app.kubernetes.io/name=my-microservice-name returns no results, despite having that label configured as seen in kubectl describe pod <my-microservice-name>-pod-name.

Ideally if there is a way to use wildcards, such as kubectl get events --field-selector involvedObject.name=*my-microservice-name*, would be the best case scenario.

Any help is greatly appreciated.

Thanks!

-- HXK
azure
kubectl
kubernetes

1 Answer

3/8/2020

I don't have azure environment, but I can show events on pods

master $ kubectl get events --field-selector involvedObject.kind=Pod
LAST SEEN   TYPE     REASON      OBJECT      MESSAGE
<unknown>   Normal   Scheduled   pod/nginx   Successfully assigned default/nginx to node01
5m13s       Normal   Pulling     pod/nginx   Pulling image "nginx"
5m8s        Normal   Pulled      pod/nginx   Successfully pulled image "nginx"
5m8s        Normal   Created     pod/nginx   Created container nginx
5m8s        Normal   Started     pod/nginx   Started container nginx

If you need target on particular pod, you should work with involvedObject.kind and involvedObject.name together.

master $ kubectl run redis --image=redis --generator=run-pod/v1
master $ kubectl run nginx --image=nginx --generator=run-pod/v1
master $ kubectl get events --field-selector involvedObject.kind=Pod,involvedObject.name=nginx
LAST SEEN   TYPE     REASON      OBJECT      MESSAGE
<unknown>   Normal   Scheduled   pod/nginx   Successfully assigned default/nginx to node01
16m         Normal   Pulling     pod/nginx   Pulling image "nginx"
16m         Normal   Pulled      pod/nginx   Successfully pulled image "nginx"
16m         Normal   Created     pod/nginx   Created container nginx
16m         Normal   Started     pod/nginx   Started container nginx

Why I knew involvedObject.kind works, because its json output shows the key is exist

        "involvedObject": {
            "apiVersion": "v1",
            "fieldPath": "spec.containers{nginx}",
            "kind": "Pod",
            "name": "nginx",
            "namespace": "default",
            "resourceVersion": "604",
            "uid": "7ebaaf99-aa9c-402b-9517-1628d99c1763"
        },

The other way you need try is jsonpath, get the output as json format

kubectl get events -o json

then copy & paste the json to https://jsonpath.com/ and play around with jsonpath practices

-- BMW
Source: StackOverflow