Python kubernetes get new events

7/23/2020

Im trying to catch events in k8s using python. The problem is that when I run the script the watch process show me all the events (current, and new). Is there a possiblitity to get only new events?

My code looks like:

    config.load_incluster_config()

    v1 = client.CoreV1Api()
    w = watch.Watch()
    for event in w.stream(v1.list_service_for_all_namespaces, timeout_seconds=0):
        service = event['object']
        if service.spec.type == 'NodePort':
            print(service.metadata.name, service.metadata.namespace, service.spec.type, service.spec.ports[0].node_port, event['type'])

With the above code I receive current events(old events) and new events, but I only want new events. Thanks in advance!!

-- fdpg
kubernetes
python

1 Answer

1/18/2022

You can use by adding if statement.

if event'type' == "ADDED" and namespace not in namespaces: print("Event: %s %s %s" % (event'type',event'object'.kind, namespace)

from kubernetes import client, config, watch
from urllib3.exceptions import ProtocolError
config.load_kube_config()
api_instance = client.CoreV1Api()

all_namespaces = api_instance.list_namespace(watch=False)
namespaces = set()
for namespace in all_namespaces.items:
    namespaces.add(namespace.metadata.name)
    #print(namespace.metadata.name)
w = watch.Watch()
try:

    for event in w.stream(api_instance.list_namespace,timeout_seconds=0):
    namespace = event['object'].metadata.name
    if event['type'] == "ADDED" and namespace not in namespaces:
        print("Event: %s %s %s" % (event['type'],event['object'].kind, namespace))
        namespaces.add(namespace)
    except ProtocolError:
    print("watchPodEvents ProtocolError, continuing..")
-- Younghwi Kim
Source: StackOverflow