Skip to main content

Bash Script to Delete Log Files Inside Pods Based on Retention Days with Different Target Folders

#!/bin/bash

# Retention days for log files (delete files older than this many days)
RETENTION_DAYS=1  # Change this to your desired retention period in days

# Namespace where the pods are located
NAMESPACE="app5-ns"  # Change this to your actual namespace

# Declare an associative array
declare -A config

# Key -> Patterns to search for in pod names
# Value -> Directory where the logs are mounted (should be the same as mountPath in Kubernetes)
config["x-server-"]="/app/Log"
config["y-server-"]="/Log"
config["z-server-"]="/Log"

# Add z-server entries from z-server02 to z-server10
for i in $(seq -w 2 10); do
    config["z-server${i}-"]="/Log"
done

# Generate PATTERN_REGEX from config keys
PATTERN_REGEX=$(printf "|%s" "${!config[@]}")
PATTERN_REGEX=${PATTERN_REGEX:1} # Remove the leading '|'

# Find all pod names that match the multiple patterns in the specified namespace
PODS=$(kubectl get pods -n "$NAMESPACE" --no-headers -o custom-columns=":metadata.name" | grep -E "$PATTERN_REGEX")

# Check if there are any matching pods
if [ -z "$PODS" ]; then
  echo "No pods found matching the patterns in namespace $NAMESPACE."
  exit 1
fi

# Iterate over each pod
for POD in $PODS; do
    # Determine the log directory based on the matching pattern
    for key in "${!config[@]}"; do
        if [[ "$POD" =~ $key ]]; then
            LOG_DIR="${config[$key]}"
            echo "Entering pod: $POD (Log Directory: $LOG_DIR)"
            
            # Check if the log directory exists and list log files
            kubectl exec -n "$NAMESPACE" "$POD" -- /bin/sh -c "find $LOG_DIR -type f -name '*.log' -mtime +$RETENTION_DAYS"
            # kubectl exec -n "$NAMESPACE" "$POD" -- /bin/sh -c "find $LOG_DIR -type f -name '*.log' -mtime +$RETENTION_DAYS -exec rm -f {} \;"

            # Confirmation message
            echo "Log cleanup complete for pod $POD."
            echo "--------------------------------------------------"
            break
        fi
    done
done