首页 > 解决方案 > Python Kubernetes 获得新事件

问题描述

我正在尝试使用 python 在 k8s 中捕获事件。问题是当我运行脚本时,监视进程会向我显示所有事件(当前的和新的)。是否有可能只获得新事件?

我的代码如下所示:

    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'])

使用上面的代码,我收到当前事件(旧事件)和新事件,但我只想要新事件。提前致谢!!

标签: pythonkubernetes

解决方案


您可以通过添加 if 语句来使用。

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..")

推荐阅读