-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocker_compose_cleanup.py
More file actions
47 lines (36 loc) · 1.37 KB
/
docker_compose_cleanup.py
File metadata and controls
47 lines (36 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
from collections import defaultdict
import docker
import requests
def clean():
client = docker.from_env()
imgs_by_project = defaultdict(list)
tags_by_project = defaultdict(list)
imgs_without_tags = []
try:
client.ping()
except (requests.ConnectionError, docker.errors.APIError):
print("Couldn't connect to Docker!")
return
# Go through all the images and group them by project (and additionally by tag, though we don't use that)
for img in client.images.list():
if not img.tags:
imgs_without_tags.append(img)
continue
for tag in img.tags:
if '_' not in tag:
continue
project = tag.split('_')[0]
imgs_by_project[project].append(img)
tags_by_project[project].append(tag)
# Print out images that don't have any tags. Those are the dangling ones that 'docker image prune' cleans up.
if imgs_without_tags:
print("Images without tags:")
print("docker image rm %s" % ' '.join(img.short_id for img in imgs_without_tags))
# Now the projects
print("Project images:")
for project, tags in sorted(tags_by_project.items()):
print(project)
print("docker image rm %s" % ' '.join(sorted(tags)))
# Make this also usable as standalone script. Because why not.
if __name__ == '__main__':
clean()