背景:由于k8s集群节点较多,需要统计到不同命名空间下的pod数量和节点上的pod数量。
实现方法:基于python实现
ns上的pod数量:
#!/usr/bin/python
import commands
namespaces = []
pod_namespaces = []
status,output = commands.getstatusoutput("kubectl get namespace")
if status == 0:
lines = output.split('\n')
for i in range(0,len(lines)):
ns = lines[i].split()[0]
if ns == 'NAME':
continue
namespaces.append(ns)
else:
print("command is not found")
exit()
sts,outp = commands.getstatusoutput("kubectl get pod -A")
line = outp.split('\n')
for i in range(0,len(line)):
pod_ns = line[i].split()[0]
if pod_ns == 'NAMESPACE':
continue
pod_namespaces.append(pod_ns)
for i in range(0,len(namespaces)):
ns = namespaces[i]
ns_num = pod_namespaces.count(ns)
print (ns,ns_num)
node上的pod数量:
#!/usr/bin/python
import commands
nodes = []
node_pod = []
status,output = commands.getstatusoutput("kubectl get nodes")
lines = output.split('\n')
for i in range(0,len(lines)):
node = lines[i].split()[0]
if node == 'NAME':
continue
nodes.append(node)
sts,outp = commands.getstatusoutput("kubectl get pod -A -o wide")
line = outp.split('\n')
for i in range(0,len(line)):
node = line[i].split()[7]
if node == 'NODE':
continue
node_pod.append(node)
for i in range(0,len(nodes)):
ns = nodes[i]
num = node_pod.count(ns)
print ns,num
|