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=21 # 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)
LOG_DIR=config["x-server-"]="/app/Log"
config["y-server-"]="/Log"
config["z-server-"]="/Log"
# ChangeAdd thisz-server entries from z-server02 to thez-server10
pathfor wherei logsin are$(seq mounted-w on2 your10); systemdo
config["z-server${i}-"]="/Log"
done
# NamespaceGenerate wherePATTERN_REGEX from config keys
PATTERN_REGEX=$(printf "|%s" "${!config[@]}")
PATTERN_REGEX=${PATTERN_REGEX:1} # Remove the podsleading are located
NAMESPACE="<namespace>" # Change this to your actual namespace
# Patterns to search for in pod names
PATTERNS=("<pattern-1", "<pattern-2", "<pattern-n")'|'
# 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
# LoopIterate throughover each pod name in the array
for POD in $PODS; do
# Determine the log directory based on the matching pattern
for key in "${PODS[!config[@]}"; do
if [[ "$POD" =~ $key ]]; then
LOG_DIR="${config[$key]}"
echo "CleaningEntering logs in podpod: $POD...POD (Log Directory: $LOG_DIR)"
# ExecuteCheck if the commandlog todirectory deleteexists and list log files in the pod older than retention days
kubectl exec -n "$NAMESPACE" "$POD" -- /bin/sh -c "find $LOG_DIR -type f -name 'town_**.log' -mtime +$RETENTION_DAYSRETENTION_DAYS"
-exec rm -f {} \;"# kubectl exec -n "$NAMESPACE" "$POD" -- /bin/sh -c "find $LOG_DIR -type f -name 'town**.log' -mtime +$RETENTION_DAYS -exec rm -f {} \;"
# Confirmation message
echo "Log cleanup complete for pod $POD."
echo "--------------------------------------------------"
break
fi
done
done