nix/scripts/container-update.sh
2025-10-10 01:24:22 +02:00

120 lines
3.3 KiB
Bash
Executable file

# Container update script
# Updates all podman containers to latest images
set -euo pipefail
# Configuration from environment (set by systemd service)
EXCLUDE_CONTAINERS="${EXCLUDE_CONTAINERS:-}"
# Convert excluded containers to array
IFS=',' read -ra EXCLUDED <<< "$EXCLUDE_CONTAINERS"
# Get all running containers
echo "Getting list of running containers..."
containers=$(podman ps --format "{{.Names}}")
if [[ -z "$containers" ]]; then
echo "No running containers found"
exit 0
fi
# Arrays to track updates
updated_containers=()
failed_containers=()
skipped_containers=()
# Update each container
for container in $containers; do
# Check if container is in exclude list
skip=false
for excluded in "${EXCLUDED[@]}"; do
if [[ "$container" == "$excluded" ]]; then
echo "Skipping excluded container: $container"
skipped_containers+=("$container")
skip=true
break
fi
done
if [[ "$skip" == true ]]; then
continue
fi
echo "Processing container: $container"
# Get current image
image=$(podman inspect "$container" --format '{{.ImageName}}')
if [[ -z "$image" ]]; then
echo "ERROR: Could not get image for container $container"
failed_containers+=("$container (no image)")
continue
fi
echo " Current image: $image"
# Get current image ID before pull
old_image_id=$(podman inspect "$container" --format '{{.Image}}')
# Pull latest image
echo " Pulling latest image..."
if podman pull "$image" 2>&1; then
echo " Image pulled successfully"
# Get new image ID after pull
new_image_id=$(podman inspect "$image" --format '{{.Id}}')
# Check if image actually changed
if [[ "$old_image_id" != "$new_image_id" ]]; then
echo " New image detected, restarting container..."
# Restart container
if podman restart "$container" 2>&1; then
echo " Container updated successfully"
updated_containers+=("$container")
else
echo " ERROR: Failed to restart container"
failed_containers+=("$container (restart failed)")
fi
else
echo " Image unchanged, skipping restart"
skipped_containers+=("$container (no update)")
fi
else
echo " ERROR: Failed to pull image"
failed_containers+=("$container (pull failed)")
fi
echo ""
done
# Print summary
echo "=== Update Summary ==="
if [[ ${#updated_containers[@]} -gt 0 ]]; then
echo "✅ Updated (${#updated_containers[@]}):"
for container in "${updated_containers[@]}"; do
echo "$container"
done
fi
if [[ ${#failed_containers[@]} -gt 0 ]]; then
echo "❌ Failed (${#failed_containers[@]}):"
for container in "${failed_containers[@]}"; do
echo "$container"
done
fi
if [[ ${#skipped_containers[@]} -gt 0 ]]; then
echo "⏭️ No updates (${#skipped_containers[@]}):"
for container in "${skipped_containers[@]}"; do
echo "$container"
done
fi
# Exit with error if any containers failed
if [[ ${#failed_containers[@]} -gt 0 ]]; then
echo "ERROR: Some containers failed to update"
exit 1
fi
echo "Container update completed successfully"