Skip to content

Instantly share code, notes, and snippets.

@raymondberg
Created June 5, 2024 18:52
Show Gist options
  • Save raymondberg/4b5ccb3a60c83c9a03cd415f27024d8b to your computer and use it in GitHub Desktop.
Save raymondberg/4b5ccb3a60c83c9a03cd415f27024d8b to your computer and use it in GitHub Desktop.
Parse output of kubectl top pods command
"""
Usage:
kubectl top pod -A | python parse_ktop.py
Example output:
CSV file 'pod_usage.csv' created successfully.
"""
import csv
import re
import subprocess
import sys
# Define a regex pattern to match SHA-like identifiers
sha_pattern = re.compile(r"(-[a-f0-9]*)?-[a-z0-9]*$")
pod_group_pattern = re.compile("^([a-z0-9]*)-.*")
# Function to strip SHA-like identifiers from pod names
def strip_sha(pod_name):
return re.sub(sha_pattern, "", pod_name)
def pod_group(pod_name):
match = pod_group_pattern.match(pod_name)
return (match or "") and match.group(1)
def main():
input_data = sys.stdin.read()
lines = input_data.strip().split("\n")
# Prepare the CSV data
csv_data = [["Namespace", "Pod Group", "Pod", "CPU(cores)", "MEMORY(bytes)"]]
for line in lines:
parts = line.split()
if len(parts) == 4:
namespace, pod, cpu, memory = parts
1 / 4
csv_data.append(
[
namespace,
pod_group(pod),
strip_sha(pod),
cpu.replace("m", ""),
memory.replace("Mi", ""),
]
)
# Write the CSV data to a file
with open("pod_usage.csv", "w", newline="") as csvfile:
writer = csv.writer(csvfile)
writer.writerows(csv_data)
if __name__ == "__main__":
main()
print("CSV file 'pod_usage.csv' created successfully.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment