Last active
January 23, 2025 07:44
-
-
Save adrianlzt/2f1f8245301ef89fb77530ff8c4eae40 to your computer and use it in GitHub Desktop.
Delete all none images and then ask the user, for each image:tag, if he wants to delete it
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import subprocess | |
def remove_image(image_id): | |
"""Safely remove a docker image.""" | |
try: | |
subprocess.run(["docker", "rmi", image_id], check=True, capture_output=True) | |
print(f" ✓ Removed: {image_id}") | |
except subprocess.CalledProcessError: | |
print(f" X Failed to remove: {image_id}") | |
def get_images(): | |
"""Get lists of all images and dangling images.""" | |
all_images_output = subprocess.run( | |
["docker", "images", "--format", "{{.Repository}}:{{.Tag}}"], | |
capture_output=True, | |
text=True, | |
check=True | |
).stdout.strip() | |
all_images = [ | |
line for line in all_images_output.splitlines() if "<none>" not in line | |
] | |
none_images_output = subprocess.run( | |
["docker", "images", "--filter", "dangling=true", "--format", "{{.ID}}"], | |
capture_output=True, | |
text=True, | |
check=True | |
).stdout.strip() | |
none_images = none_images_output.splitlines() | |
return all_images, none_images | |
def main(): | |
all_images, none_images = get_images() | |
if not all_images and not none_images: | |
print("No Docker images found to delete.") | |
return | |
print("------------------------------------------------------") | |
print("Found these images:") | |
if none_images: | |
print(" ** Removing <none> images...") | |
for image_id in none_images: | |
remove_image(image_id) | |
if all_images: | |
print(" ** Reviewing other images...") | |
for image in all_images: | |
response = input(f" Delete image '{image}'? (y/N): ").strip().lower() | |
if response in ("y", "yes"): | |
remove_image(image) | |
else: | |
print(f" - Skipped: {image}") | |
print("------------------------------------------------------") | |
print("Image cleanup finished.") | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment