如何同步Prometheus、Kubewatch与Kubernetes集群获取历史事件
Kubernetes集群历史事件获取方案
方案1:Kubewatch + Prometheus 配置实现
- 步骤1:部署Kubewatch并开启Prometheus输出
优先使用helm安装Kubewatch:helm install kubewatch bitnami/kubewatch --namespace kubewatch --create-namespace
安装时修改values.yaml配置,开启指标暴露并过滤Pod事件:metrics:
enabled: true
serviceMonitor:
enabled: true
resources:
pods: true关闭其他不需要的资源事件监听,比如deployments、daemonsets等 - 步骤2:配置Prometheus采集
确认Kubewatch的metrics服务被Prometheus自动发现,或手动在Prometheus配置中添加Kubewatch的采集地址,kubewatch_event_*系列指标即为Kubernetes事件数据,指标标签会携带Pod名称、命名空间、事件原因、事件消息、事件类型等核心字段。 - 步骤3:Python从Prometheus拉取数据转字典
先安装依赖库:pip install prometheus-api-client
参考代码示例:from prometheus_api_client import PrometheusConnect # 替换为你的Prometheus访问地址 prom = PrometheusConnect(url="http://prometheus-svc:9090", disable_ssl=True) # 查询所有Pod事件指标 query = 'sum by (pod, namespace, reason, message, event_type) (kubewatch_event_count)' result = prom.custom_query(query) # 转换为Python字典列表格式 pod_event_list = [ { "pod_name": item["metric"].get("pod"), "namespace": item["metric"].get("namespace"), "event_reason": item["metric"].get("reason"), "event_message": item["metric"].get("message"), "event_type": item["metric"].get("event_type"), "event_count": int(item["value"][1]) } for item in result ]
替代解决方案(更轻量无额外依赖)
替代1:直接调用Kubernetes原生API获取事件
该方案无需部署任何第三方中间件,是最推荐的实现方式。Kubernetes本身将Event作为标准API资源提供访问,默认保留时长为1小时,可通过修改kube-apiserver的--event-ttl参数调整保留时间。
- 先安装官方Python SDK:
pip install kubernetes - 参考代码示例:
from kubernetes import client, config # 集群内运行使用config.load_incluster_config(),集群外本地运行使用config.load_kube_config() config.load_kube_config() core_api = client.CoreV1Api() # 拉取全集群所有事件 all_events = core_api.list_event_for_all_namespaces() # 筛选Pod相关事件并直接转为Python字典 pod_event_list = [] for event in all_events.items: if event.involved_object.kind == "Pod": # 原生对象直接调用to_dict()即可得到标准Python字典格式 pod_event_list.append(event.to_dict())
替代2:事件持久化方案(适用于长期保留历史事件)
如果需要存储超过kube-apiserverTTL的事件,可使用以下方案:
- Event Exporter:轻量导出工具,可将Kubernetes事件导出到MySQL、Elasticsearch等存储,之后Python直接连接数据库查询数据即可转为字典格式
- Loki + Promtail:配置Promtail采集事件日志存储到Loki,通过LogQL查询后调用Loki API获取数据,直接解析为Python字典即可
内容的提问来源于stack exchange,提问作者Dragnoid99
相关产品推荐
相关产品推荐

