Here’s the same content with backlinks added, optimized for on-page SEO while preserving the original words:
Monitor Pod Health in Kubernetes
In this guide, we will create a Bash script to monitor the health of Kubernetes pods across all namespaces. This script will automate the retrieval of pod statuses, display their health conditions, and generate a report for easy review. It also includes icons for enhanced readability in the terminal.
Script Overview
The script will:
- Check prerequisites (ensure kubectl is installed and configured).
- List all namespaces in the cluster.
- Retrieve pod statuses for each namespace.
- Categorize pod health into statuses like Running, Pending, or Failed.
- Optionally generate a report or take action if unhealthy pods are detected.
Script
Here’s the complete script:
#!/bin/bash
# Kubernetes Pod Health Monitor Script
# Author: [Your Name]
# Date: [Date]
# Version: 1.0
# Icons for display
CHECK="\u2714" # ✔
CROSS="\u274C" # ✘
INFO="\u2139" # ℹ
WARNING="\u26A0" # âš
# Function: Check if kubectl is installed
function check_kubectl() {
if ! command -v kubectl &> /dev/null; then
echo -e "${CROSS} Error: kubectl is not installed. Please install kubectl and configure access to the cluster."
exit 1
else
echo -e "${CHECK} kubectl is installed."
fi
}
# Function: Check cluster connectivity
function check_cluster_access() {
if ! kubectl cluster-info > /dev/null 2>&1; then
echo -e "${CROSS} Error: Unable to connect to the Kubernetes cluster. Please check your kubeconfig."
exit 1
else
echo -e "${CHECK} Connected to the Kubernetes cluster."
fi
}
# Function: Get all namespaces
function get_namespaces() {
echo -e "${INFO} Retrieving namespaces..."
kubectl get namespaces -o custom-columns=NAME:.metadata.name --no-headers
}
# Function: Monitor pod health across namespaces
function monitor_pods() {
echo -e "${INFO} Monitoring pod health across all namespaces..."
namespaces=$(get_namespaces)
echo -e "${INFO} Found the following namespaces:"
echo "$namespaces"
# Initialize counters
total_pods=0
healthy_pods=0
unhealthy_pods=0
echo -e "\n${INFO} Pod health report:"
echo -e "Namespace\tPod Name\t\tStatus"
# Iterate through each namespace
for ns in $namespaces; do
pods=$(kubectl get pods -n "$ns" -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.phase}{"\n"}{end}')
while read -r pod status; do
total_pods=$((total_pods + 1))
if [[ $status == "Running" ]]; then
healthy_pods=$((healthy_pods + 1))
echo -e "$ns\t$pod\t\t${CHECK} $status"
else
unhealthy_pods=$((unhealthy_pods + 1))
echo -e "$ns\t$pod\t\t${CROSS} $status"
fi
done <<< "$pods"
done
echo -e "\n${INFO} Summary:"
echo -e "Total Pods: $total_pods"
echo -e "Healthy Pods: ${CHECK} $healthy_pods"
echo -e "Unhealthy Pods: ${CROSS} $unhealthy_pods"
}
# Function: Generate a report
function generate_report() {
echo -e "${INFO} Generating pod health report..."
report_file="pod_health_report_$(date +%F).txt"
kubectl get pods --all-namespaces -o wide > "$report_file"
echo -e "${CHECK} Report saved to $report_file"
}
# Main script starts here
echo "=== Kubernetes Pod Health Monitor ==="
# Step 1: Check prerequisites
check_kubectl
check_cluster_access
# Step 2: Monitor pod health
monitor_pods
# Step 3: Generate optional report
read -p "Do you want to generate a detailed report? (yes/no): " generate
if [[ $generate == "yes" ]]; then
generate_report
fi
echo -e "${CHECK} Script execution completed."
Monitor Pod Health in Kubernetes
1. Checking Prerequisites
The script first ensures that kubectl is installed and accessible. This is done using:
if ! command -v kubectl &> /dev/null; then
If kubectl is unavailable, the script terminates with an error.
It also verifies connectivity to the Kubernetes cluster:
if ! kubectl cluster-info > /dev/null 2>&1; then
2. Listing All Namespaces in Kubernetes
The script retrieves a list of namespaces using:
kubectl get namespaces -o custom-columns=NAME:.metadata.name --no-headers
For more details on namespaces, see Kubernetes Namespaces.
3. Monitoring Pod Health
For each namespace, the script retrieves pod names and their statuses:
pods=$(kubectl get pods -n "$ns" -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.phase}{"\n"}{end}')
Pod statuses are categorized into healthy (Running) and unhealthy (any other status). For details on pod statuses, see Pod Lifecycle.
4. Generating a Summary
The script provides a summary of total, healthy, and unhealthy pods:
echo -e "Total Pods: $total_pods"
echo -e "Healthy Pods: ${CHECK} $healthy_pods"
echo -e "Unhealthy Pods: ${CROSS} $unhealthy_pods"
5. Generating a Detailed Report
If the user opts to generate a report, the script saves detailed pod information to a file:
kubectl get pods --all-namespaces -o wide > "$report_file"
For more options with kubectl get, visit the kubectl Cheat Sheet.
Possible Enhancements
- Alerting System: Integrate notifications via Slack or email for unhealthy pods.
- Threshold-Based Actions: Automatically restart pods using kubectl commands if a threshold of unhealthy pods is crossed.
- Expanded Reporting: Include pod events or logs for debugging.
Learn more about: monitor kubernetes cluster with grafana
