🐶
Kubernetes

kubectl Get Events Sorted by Field & Filter Output

By Jan on 02/10/2025

Learn how to use kubectl effectively to get events sorted by specific fields and display only the event details you need.

kubectl Get Events Sorted by Field & Filter Output

Table of Contents

Introduction

Kubernetes events provide valuable insights into the activities within your cluster. They offer a chronological record of changes, errors, and other significant occurrences, helping you understand the behavior and health of your applications and resources. This guide provides a set of practical kubectl commands to effectively list and analyze events in your Kubernetes cluster.

Step-by-Step Guide

  1. List events in the default namespace:

    kubectl get events
  2. List events in all namespaces:

    kubectl get events --all-namespaces
  3. List events for a specific resource:

    kubectl get events --for=pod/web-pod-13je7
  4. List events and watch for new events:

    kubectl get events --watch
  5. List events and filter by type:

    kubectl get events --types=Warning,Normal
  6. Output events in YAML format:

    kubectl get events -o yaml
  7. Print specific fields of events:

    kubectl get events -o custom-columns=LAST_SEEN:.lastTimestamp,TYPE:.type,REASON:.reason,OBJECT:.involvedObject.kind/name,MESSAGE:.message
  8. Sort events by a specific field (e.g., last seen time): Note: kubectl get events doesn't natively support sorting by last seen time. You can pipe the output to sort command for sorting.

    kubectl get events -o go-template='{{range .items}}{{.lastTimestamp}}{"\t"}}{{.type}}{"\t"}}{{.reason}}{"\t"}}{{.involvedObject.kind}}/{{.involvedObject.name}}{"\t"}}{{.message}}{{"\n"}}{{end}}' | sort

    This command uses go-template to format the output and then pipes it to the sort command for sorting.

Code Example

This Python code demonstrates how to use the Kubernetes API to list and filter events within a Kubernetes cluster. It covers listing events in a specific namespace, across all namespaces, for a particular resource, and filtering by event type. The code also shows how to output events in YAML format and access specific event fields.

from kubernetes import client, config

# Load Kubernetes configuration
config.load_kube_config()

# Create an instance of the Kubernetes API client
v1 = client.CoreV1Api()

# 1. List events in the default namespace
print("Events in the default namespace:")
events = v1.list_namespaced_event("default")
for event in events.items:
    print(f"  {event.metadata.name}: {event.reason}")

# 2. List events in all namespaces
print("\nEvents in all namespaces:")
events = v1.list_event_for_all_namespaces()
for event in events.items:
    print(f"  {event.metadata.namespace}/{event.metadata.name}: {event.reason}")

# 3. List events for a specific resource
print("\nEvents for pod/web-pod-13je7:")
events = v1.list_namespaced_event("default", field_selector="involvedObject.name=web-pod-13je7")
for event in events.items:
    print(f"  {event.reason}")

# 4. List events and watch for new events (not shown here, requires continuous loop)

# 5. List events and filter by type
print("\nWarning and Normal events:")
events = v1.list_namespaced_event("default", field_selector="type=Warning,type=Normal")
for event in events.items:
    print(f"  {event.type}: {event.reason}")

# 6. Output events in YAML format
print("\nEvents in YAML format:")
events = v1.list_namespaced_event("default")
print(events)

# 7. Print specific fields of events
print("\nSpecific fields of events:")
events = v1.list_namespaced_event("default")
for event in events.items:
    print(
        f"  Last Seen: {event.last_timestamp}, Type: {event.type}, Reason: {event.reason}, Object: {event.involved_object.kind}/{event.involved_object.name}, Message: {event.message}"
    )

# 8. Sort events by a specific field (e.g., last seen time) - Not supported natively by the client, requires manual sorting

This code uses the Kubernetes Python client library to interact with the Kubernetes API and retrieve event information. You can modify and extend this code to suit your specific needs.

Remember to install the Kubernetes Python client library:

pip install kubernetes

This code provides a starting point for working with Kubernetes events using Python.

Additional Notes

General Understanding:

  • Importance: Events are crucial for understanding the historical behavior of your cluster and debugging issues. They provide context for changes in state and potential problems.
  • Event Lifecycle: Events are automatically created by Kubernetes components and have a limited lifespan. They are not persistent storage and will be eventually aged out.
  • Event Sources: Pay attention to the SOURCE field to understand which component generated the event (e.g., kubelet, scheduler, controller-manager).

Command Specific Notes:

  • --for flag: This flag is very useful for zeroing in on events related to a specific deployment, pod, replicaset, etc.
  • --watch flag: For real-time monitoring and troubleshooting, the --watch flag provides a continuous stream of events as they happen.
  • Filtering and Sorting: While kubectl get events doesn't directly support sorting by last seen time, using go-template and piping to sort offers flexibility. You can adapt this approach to sort by other fields as well.
  • Custom Columns: The -o custom-columns flag is powerful for tailoring the output to show only the information you need.
  • Programmatic Access: The Python code example demonstrates how to interact with the Kubernetes API to retrieve and process events programmatically, allowing for more complex analysis and automation.

Beyond the Basics:

  • Event Persistence: For long-term storage and analysis of events, consider using a logging and monitoring solution that integrates with Kubernetes, such as Elasticsearch, Fluentd, and Kibana (EFK) stack or Prometheus.
  • Event Rate Limiting: In large clusters with high activity, the volume of events can be significant. Be mindful of potential performance impacts and configure event rate limiting if necessary.
  • Custom Events: You can create your own custom events within your applications to provide additional context and insights into application-specific events.

By mastering these kubectl commands and understanding the nature of Kubernetes events, you'll be well-equipped to monitor, troubleshoot, and gain deeper insights into your cluster's operations.

Summary

This table summarizes various kubectl get events commands for retrieving and filtering Kubernetes events:

Action Command Description
List events in the default namespace kubectl get events Retrieves all events within the current namespace.
List events in all namespaces kubectl get events --all-namespaces Retrieves events across all namespaces in the cluster.
List events for a specific resource kubectl get events --for=pod/web-pod-13je7 Retrieves events associated with a specific resource, like a pod.
Watch for new events kubectl get events --watch Continuously displays new events as they occur.
Filter events by type kubectl get events --types=Warning,Normal Retrieves events of specified types, like "Warning" or "Normal".
Output events in YAML format kubectl get events -o yaml Displays events in YAML format for easier parsing.
Print specific event fields kubectl get events -o custom-columns=LAST_SEEN:.lastTimestamp,TYPE:.type,REASON:.reason,OBJECT:.involvedObject.kind/name,MESSAGE:.message Customizes the output to show specific event fields.
Sort events by last seen time (using external command) kubectl get events -o go-template='{{range .items}}{{.lastTimestamp}}{"\t"}}{{.type}}{"\t"}}{{.reason}}{"\t"}}{{.involvedObject.kind}}/{{.involvedObject.name}}{"\t"}}{{.message}}{{"\n"}}{{end}}' | sort Uses go-template to format output and pipes it to the sort command for sorting by last seen time.

Conclusion

Kubernetes events are essential for understanding the inner workings and health of your cluster. By mastering the kubectl commands for listing, filtering, and analyzing these events, you can effectively monitor your applications, troubleshoot issues, and gain deeper insights into your cluster's behavior. Whether you prefer the command line or programmatic access through the Kubernetes API, the tools and techniques outlined in this guide provide a solid foundation for working with Kubernetes events. Remember to explore additional resources and experiment with different commands and options to tailor event analysis to your specific needs. By integrating event monitoring into your workflow, you can ensure the smooth operation and efficient management of your Kubernetes deployments.

References

  • How to Collect Kubernetes Events and Extract Values How to Collect Kubernetes Events and Extract Values | Learn what Kubernetes Events are, including their various types. Explore how to collect event data using two key commands: kubectl describe and kubectl get events, and discuss the use of different flags with kubectl get events for enhanced filtering and sorting.
  • sorting by inconsistently formatted elapsed time field ( k8s events by ... sorting by inconsistently formatted elapsed time field ( k8s events by ... | Dec 13, 2022 ... Will try one and see if ... What kubectl command can I use to get events sorted by specific fields and print only specific details of events?
  • kubectl get events doesnt sort events by last seen time. · Issue #29838 kubectl get events doesnt sort events by last seen time. · Issue #29838 | Here is one example see below:- LASTSEEN FIRSTSEEN COUNT NAME KIND SUBOBJECT TYPE REASON SOURCE MESSAGE 13m 13m 1 nginx-deployment-3392909933-1tfwp Pod Normal Scheduled {default-scheduler } Success...
  • kubectl - Kubernetes sort pods by age - Stack Overflow kubectl - Kubernetes sort pods by age - Stack Overflow | Jul 25, 2017 ... What kubectl command can I use to get events sorted by specific fields and print only specific details of events? 22 · Timeline of kubernetes ...
  • List Events with kubectl | Warp List Events with kubectl | Warp | Learn how to list and filter events in Kubernetes cluster by namespace, pod name and more using the kubectl command.
  • kubectl events | Kubernetes kubectl events | Kubernetes | Synopsis Display events. Prints a table of the most important information about events. You can request events for a namespace, for all namespace, or filtered to only those pertaining to a specified resource. kubectl events [(-o|--output=)json|yaml|name|go-template|go-template-file|template|templatefile|jsonpath|jsonpath-as-json|jsonpath-file] [--for TYPE/NAME] [--watch] [--types=Normal,Warning] Examples # List recent events in the default namespace kubectl events # List recent events in all namespaces kubectl events --all-namespaces # List recent events for the specified pod, then wait for more events and list them as they arrive kubectl events --for pod/web-pod-13je7 --watch # List recent events in YAML format kubectl events -oyaml # List recent only events of type 'Warning' or 'Normal' kubectl events --types=Warning,Normal Options -A, --all-namespaces If present, list the requested object(s) across all namespaces.
  • Troubleshoot With Kubernetes Events | Datadog Troubleshoot With Kubernetes Events | Datadog | Learn how to collect, monitor, and use Kubernetes events to root cause and troubleshoot problems with your containerized workloads.
  • kubectl Quick Reference | Kubernetes kubectl Quick Reference | Kubernetes | This page contains a list of commonly used kubectl commands and flags. Note:These instructions are for Kubernetes v1.32. To check the version, use the kubectl version command. Kubectl autocomplete BASH source <(kubectl completion bash) # set up autocomplete in bash into the current shell, bash-completion package should be installed first. echo "source <(kubectl completion bash)" >> ~/.bashrc # add autocomplete permanently to your bash shell. You can also use a shorthand alias for kubectl that also works with completion:
  • Kubectl Cheat Sheet - 15 Kubernetes Commands & Objects Kubectl Cheat Sheet - 15 Kubernetes Commands & Objects | See the helpful list of each commonly used category or component of Kubernetes (K8S) with appropriate kubectl commands for quick reference!

Were You Able to Follow the Instructions?

😍Love it!
😊Yes
😐Meh-gical
😞No
🤮Clickbait