49 lines
1.6 KiB
Python
49 lines
1.6 KiB
Python
# -*- coding: utf-8 -*-
|
|
import requests
|
|
import subprocess
|
|
|
|
# 获取 node-exporter 的 Pod 名称和节点名称
|
|
pod_info_bytes = subprocess.check_output("kubectl -n monitor get po -owide -l app=node-exporter --no-headers", shell=True)
|
|
# 将二进制数据转换为字符串并按行分割
|
|
# pod_info = pod_info_bytes.strip().split('\n')
|
|
pod_info = pod_info_bytes.decode('utf-8').strip().split('\n')
|
|
# 提取 Pod 名称和节点名称
|
|
pod_names = [info.split()[0] for info in pod_info]
|
|
node_ips = [info.split()[5] for info in pod_info]
|
|
node_names = [info.split()[6] for info in pod_info]
|
|
|
|
# 确保名称数量一致
|
|
if len(pod_names) != len(node_names):
|
|
print("Error: 节点数量与 Pod 数量不匹配.")
|
|
exit(1)
|
|
|
|
|
|
|
|
# 定义 Consul agent 的端点
|
|
consul_endpoint = "http://consul.opsx.top/v1/agent/service/register"
|
|
|
|
# 遍历每个 Pod 并将服务注册到 Consul
|
|
for pod_name,node_ip, node_name in zip(pod_names, node_ips,node_names):
|
|
# print("pod: {} ip:{} node: {}".format(pod_name, node_ip,node_name))
|
|
# 定义服务注册的数据
|
|
data = {
|
|
"id": f"{node_name}-{pod_name}",
|
|
"name": "node-exporter",
|
|
"address": f"{node_ip}",
|
|
"port": 9100,
|
|
"checks": [{
|
|
"http": f"http://{node_ip}:9100/metrics",
|
|
"interval": "5s"
|
|
}]
|
|
}
|
|
print(data)
|
|
|
|
# 发送 PUT 请求以注册服务
|
|
response = requests.put(consul_endpoint, json=data)
|
|
|
|
# 检查响应状态
|
|
if response.status_code == 200:
|
|
print(f"服务 {pod_name} 注册成功.")
|
|
else:
|
|
print(f"无法注册服务 {pod_name}. 状态码: {response.status_code}")
|
|
print(response.text) |