Skip to content

Instantly share code, notes, and snippets.

@korutx
Created December 14, 2024 17:03
Show Gist options
  • Save korutx/07fd9f6c161407629f4acbd9d84fea14 to your computer and use it in GitHub Desktop.
Save korutx/07fd9f6c161407629f4acbd9d84fea14 to your computer and use it in GitHub Desktop.
Kubectl get pods sorted and colored by node
#!/bin/bash
# Script to display Kubernetes pods grouped and color-coded by node
kubectl get pods -o wide | sort -k7 | awk '
BEGIN {
# Define ANSI color codes for groups
colors[1] = "\033[1;31m"; # Red
colors[2] = "\033[1;32m"; # Green
colors[3] = "\033[1;33m"; # Yellow
colors[4] = "\033[1;34m"; # Blue
colors[5] = "\033[1;35m"; # Magenta
colors[6] = "\033[1;36m"; # Cyan
reset = "\033[0m"; # Reset color
}
NR == 1 { print; next } # Print the header
{
# Group by Node (column 7)
node = $7;
if (!(node in seen)) {
seen[node] = ++count; # Assign a unique group ID for each node
}
color = colors[seen[node] % 6 + 1]; # Cycle through colors
printf "%s%s%s\n", color, $0, reset;
}'
@korutx
Copy link
Author

korutx commented Dec 14, 2024

kgpwc.sh

This script enhances Kubernetes kubectl functionality by sorting and color-coding pods based on the nodes they are running on. It provides an easy-to-read visualization for Kubernetes administrators managing multiple nodes in a cluster.

Features

  • Node-based Sorting: The script uses kubectl get pods -o wide and sorts the pods by the node column to group them.
  • Color-coded Output: Assigns a unique color to each node, making it easier to visually differentiate between pods running on different nodes.
  • Customizable: You can easily modify the script to adjust the colors or adapt it to other Kubernetes objects.

Installation

  1. Download the script and save it to a directory included in your $PATH (e.g., ~/bin):

    curl -o ~/bin/kgpwc https://gist.githubusercontent.com/<your-gist-id>/raw/kgpwc.sh
  2. Make the script executable:

    chmod +x ~/bin/kgpwc
  3. Ensure the ~/bin directory is in your $PATH. Add this line to your ~/.zshrc or ~/.bashrc if it’s not already there:

    export PATH="$HOME/bin:$PATH"
  4. Reload your shell configuration:

    source ~/.zshrc

Usage

Run the script directly in your terminal:

kgpwc

This will output a list of Kubernetes pods, sorted and grouped by node, with each node visually distinguished by a unique color.

Example Output

image

Troubleshooting

  1. No Colors in Output:

    • Make sure your terminal supports ANSI colors. Test it by running:
      echo -e "\033[1;31mRed\033[0m Normal"
  2. kubectl Issues:

    • Ensure kubectl is correctly configured to communicate with your Kubernetes cluster:
      kubectl cluster-info
  3. Script Not Found:

    • Ensure the script is in a directory listed in your $PATH and is marked as executable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment