Skip to content

Commit 6832853

Browse files
authored
Added the Auto Old Docker Images Delete Script
1 parent 4c89e2b commit 6832853

File tree

2 files changed

+142
-0
lines changed

2 files changed

+142
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Auto Cleanup of Older Versions of Docker Images present in a System
2+
3+
During Containerized Deployment of applications, often some VMs are particularly allotted for building the Docker Containers. Whenever a new code change takes place, automatically the CI/CD pipeline triggers the build of a new container containing the latest codes.
4+
5+
Since the VMs have a fixed Disk Size, often storage issues arise, which lead to failure in the building of the containers leading to breakage in the CICD pipeline.
6+
7+
Therefore it's necessary to remove older versions of the container images on a regular basis to avoid storage issues.
8+
A script has to be written, which would perform the clean-up process based on the image tags.
9+
10+
It will preserve all the docker images containing the latest tag.
11+
For a particular repository, the tag with the highest number would be preserved.
12+
A provision is made to add exception images that would be never stopped.
13+
14+
---
15+
<br>
16+
17+
## Rules Implemented:
18+
19+
1. All images with 'latest' tag would not be touched.
20+
2. For a particular repository, the tag with the highest number would be preserved.
21+
3. A provision is made to add exception images which would be never stopped.

old_docker_images_auto_delete/main.py

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
# Python Program to auto-delete old docker images
2+
"""
3+
Rules:
4+
5+
1. All images with 'latest' tag would not be touched.
6+
2. For a particular repository, the tag with the highest number would be preserved.
7+
3. A provision is made to add exception images which would be never stopped.
8+
9+
"""
10+
11+
import subprocess as sp
12+
import re
13+
import operator, itertools
14+
15+
class DeleteImage:
16+
17+
def __init__(self):
18+
self.imgList = []
19+
self.hashList = []
20+
21+
22+
# Storing All the Docker Image Details Found on the System to a File
23+
def getAll(self):
24+
file = open("temp.txt","r+")
25+
file.truncate(0)
26+
sp.run("sudo docker image list --format '{{.Repository}}~{{.Tag}}' >> temp.txt", shell=True , capture_output=True)
27+
file.close()
28+
29+
30+
#Add other exceptions here
31+
def isExcluded(self , tag):
32+
33+
reg = r"alpine|buster|slim|latest" #Excluding all the images with Alpine, Buster, Slim & Latest Tags
34+
m = re.search(reg, tag)
35+
if m != None:
36+
return 0
37+
return 1
38+
39+
# Loading data from the File to the Python program
40+
def loadAll(self):
41+
f = open("temp.txt", "r")
42+
43+
for line in f:
44+
line = line.rstrip("\n")
45+
image = line.split('~')
46+
if self.isExcluded(image[1]):
47+
48+
regex = r"^(((\d+\.)?(\d+\.)?(\*|\d+)))(\-(dev|stage|prod))*$"
49+
match = re.search(regex, image[1])
50+
51+
imgDict = { 'Repository':image[0] , 'Tag': match.group(2) }
52+
self.imgList.append(imgDict)
53+
f.close()
54+
55+
56+
def manData(self):
57+
key = operator.itemgetter('Repository')
58+
b = [{'Repository': x, 'Tag': [d['Tag'] for d in y]}
59+
for x, y in itertools.groupby(sorted(self.imgList, key=key), key=key)]
60+
61+
self.imgList.clear()
62+
self.imgList = b.copy()
63+
64+
65+
# Sorting Tags according to the Version Numbers
66+
def sortTag(self):
67+
68+
for img in self.imgList:
69+
temp = img['Tag'].copy()
70+
71+
for n, i in enumerate(img['Tag']):
72+
img['Tag'][n] = int(i.replace('.', ''))
73+
74+
maxLen = len(str(max(abs(x) for x in img['Tag'])))
75+
templateString = '{:<0' + str(maxLen) + '}'
76+
finalList = []
77+
78+
for n, i in enumerate(img['Tag']):
79+
finalList.append(templateString.format(i))
80+
81+
for i in range(0 , len(img['Tag'])):
82+
hashMap = { 'TagsManipulated': finalList[i] , 'TagsOriginal': temp[i] }
83+
self.hashList.append(hashMap)
84+
85+
finalList.sort()
86+
87+
img['Tag'].clear()
88+
img['Tag'].extend(finalList[:-1])
89+
90+
print(self.hashList)
91+
print (self.imgList)
92+
93+
94+
def hashFunc(self , tag):
95+
for hashMap in self.hashList:
96+
if tag == hashMap['TagsManipulated']:
97+
t = hashMap['TagsOriginal']
98+
break
99+
else:
100+
t = 'Error in Manipulation'
101+
return t
102+
103+
# Running the Docker RMI Command to Delete the Older Versions
104+
def removeImage(self):
105+
for img in self.imgList:
106+
if img['Tag']:
107+
for tag in img['Tag']:
108+
val = self.hashFunc(tag)
109+
imageURL = img['Repository'] + ":" + val
110+
print ("Deleting Image : " + imageURL )
111+
sp.run("sudo docker rmi " + imageURL, shell=True , capture_output=True)
112+
113+
# Main Function
114+
if __name__ == "__main__":
115+
116+
docker = DeleteImage()
117+
docker.getAll()
118+
docker.loadAll()
119+
docker.manData()
120+
docker.sortTag()
121+
docker.removeImage()

0 commit comments

Comments
 (0)