#!/bin/bash # ============================================================================== # K3s Disk Cleaner # Purpose: Prune unused container images and stopped containers to free disk space. # ============================================================================== # Threshold: Only prune if disk usage is above this percentage (optional logic) # Currently set to run unconditionally, but you can add checks using 'df'. echo "Starting K3s Cleanup Routine..." echo "------------------------------------------------" # Check if crictl exists (standard in K3s/K3OS) if ! command -v crictl &> /dev/null; then echo "Error: crictl command not found." exit 1 fi echo "1. Removing stopped containers..." # List stopped containers and remove them # We suppress output for cleanliness, or remove > /dev/null to see details crictl rm $(crictl ps -a | grep Exited | awk '{print $1}') 2>/dev/null if [ $? -eq 0 ]; then echo " Stopped containers removed." else echo " No stopped containers found or error occurred." fi echo "2. Pruning unused images..." # This removes images not currently used by any container crictl rmi --prune echo "------------------------------------------------" echo "Disk Usage after cleanup:" df -h /var/lib/rancher echo "Done."