Managing multiple Kubernetes clusters? This script is your morning coffee - one loop to rule them all.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
#!/bin/bash
export KUBECONFIGDIR=~/.kube/cur

for each in $(ls $KUBECONFIGDIR/)
do
  export KUBECONFIG=$KUBECONFIGDIR/$each
  echo current Context: $(kubectl config get-contexts | awk '{print $2}')

  kubectl get pod -A -o wide > /tmp/pods.a
  kubectl top nodes | while read line; do
    NODE=`echo $line | awk '{print $1}'`
    export NOS=`cat /tmp/pods.a | grep $NODE | grep Running | wc -l`
    export CPUC=`echo $line | awk '{print $2}'`
    export CPUP=`echo $line | awk '{print $3}'`
    export MEMB=`echo $line | awk '{print $4}'`
    export MEMP=`echo $line | awk '{print $5}'`
    echo NODE: $NODE, NOS=$NOS, CPUC=$CPUC, CPUP=$CPUP, MEMB=$MEMB, MEMP=$MEMP
  done
done

unset KUBECONFIG

Prerequisites:

  • Multiple kubeconfig files stored in ~/.kube/cur/
  • Each file represents a different cluster context

Output format:

1
2
3
4
5
6
current Context: prod-cluster-1
NODE: node-1, NOS=12, CPUC=2000m, CPUP=45%, MEMB=8Gi, MEMP=67%
NODE: node-2, NOS=8, CPUC=1500m, CPUP=32%, MEMB=6Gi, MEMP=54%

current Context: prod-cluster-2
NODE: node-1, NOS=15, CPUC=2200m, CPUP=48%, MEMB=9Gi, MEMP=71%

Variables:

  • NOS: Number of running pods
  • CPUC: CPU usage (cores/millicores)
  • CPUP: CPU usage percentage
  • MEMB: Memory usage (bytes/GB)
  • MEMP: Memory usage percentage