What kubectl command can I use to get events sorted by specific fields and print only specific details of events?

KubernetesKubectlGo Templates

Kubernetes Problem Overview


I need to print only specific fields of Kubernetes Events, sorted by a specific field.

This is to help me gather telemetry and analytics about my namespace

How could I do that?

Kubernetes Solutions


Solution 1 - Kubernetes

kubectl get events --sort-by='.lastTimestamp'

Solution 2 - Kubernetes

> Following command does it.

It prints the events sorted by timestamp of creation.

It also users go-template to filter out specific fields of the kubernetes-event object.

kubectl get events  --sort-by='.metadata.creationTimestamp'  -o 'go-template={{range .items}}{{.involvedObject.name}}{{"\t"}}{{.involvedObject.kind}}{{"\t"}}{{.message}}{{"\t"}}{{.reason}}{{"\t"}}{{.type}}{{"\t"}}{{.firstTimestamp}}{{"\n"}}{{end}}'

Solution 3 - Kubernetes

I am using the following command to sort it after timestamp

kubectl get event --all-namespaces --sort-by='.metadata.managedFields[0].time'

For filtering out the information you can of course combine it with the go-template described by @suryakrupa or with jq described by @Chris Stryczynski

Solution 4 - Kubernetes

If you don't mind seeing the output as JSON:

kubectl get event -o json | jq '.items |= sort_by(.lastTimestamp)'

This requires jq.

Solution 5 - Kubernetes

Here's the Bash function I use:

function kubectl-events {
	{
		echo $'TIME\tNAMESPACE\tTYPE\tREASON\tOBJECT\tSOURCE\tMESSAGE';
		kubectl get events -o json "$@" \
			| jq -r  '.items | map(. + {t: (.eventTime//.lastTimestamp)}) | sort_by(.t)[] | [.t, .metadata.namespace, .type, .reason, .involvedObject.kind + "/" + .involvedObject.name, .source.component + "," + (.source.host//"-"), .message] | @tsv';
	} \
		| column -s $'\t' -t \
		| less -S
}

You can use it like: kubectl-events -A, kubectl-events -n foo, etc.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsuryakrupaView Question on Stackoverflow
Solution 1 - KubernetesehbelloView Answer on Stackoverflow
Solution 2 - KubernetessuryakrupaView Answer on Stackoverflow
Solution 3 - KubernetesTimtationView Answer on Stackoverflow
Solution 4 - KubernetesChris StryczynskiView Answer on Stackoverflow
Solution 5 - KubernetesSam MorrisView Answer on Stackoverflow