-
Notifications
You must be signed in to change notification settings - Fork 9
91 lines (78 loc) · 3.15 KB
/
cleanup-old-docker-images.yml
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
name: Cleanup Old Docker Images > 6 months by the scheduler
on:
push:
branches-ignore:
- master
jobs:
cleanup:
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v2
- name: Login to DockerHub
uses: docker/login-action@v1
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: List Docker Hub images and delete ones matching the pattern
run: |
REPO="spryker/php"
curl -s "https://hub.docker.com/v2/repositories/${REPO}/tags?page_size=1000" > tags.json
TODAY=$(date +%s)
THRESHOLD=$((180 * 24 * 60 * 60)) # 180 days in seconds
# Regex pattern to match tags that end with a hash (40-character hexadecimal)
HASH_PATTERN=".*-[a-f0-9]{40}$"
IMAGES_DELETED=false
DELETED_IMAGES=""
for TAG in $(jq -r '.results[] | @base64' < tags.json); do
_jq() {
echo ${TAG} | base64 --decode | jq -r ${1}
}
TAG_NAME=$(_jq '.name')
LAST_UPDATED=$(_jq '.last_updated')
LAST_UPDATED_DATE=$(date -d "${LAST_UPDATED}" +%s)
AGE=$((TODAY - LAST_UPDATED_DATE))
if [[ ${AGE} -ge ${THRESHOLD} ]] && [[ ${TAG_NAME} =~ ${HASH_PATTERN} ]]; then
echo "Deleting image tag ${TAG_NAME} (last updated: ${LAST_UPDATED})"
IMAGES_DELETED=true
DELETED_IMAGES="${DELETED_IMAGES}\n${TAG_NAME}"
# Uncomment the following lines to enable image deletion
curl -X DELETE \
-u "${{ secrets.DOCKER_USERNAME }}:${{ secrets.DOCKER_PASSWORD }}" \
"https://hub.docker.com/v2/repositories/${REPO}/tags/${TAG_NAME}/"
fi
done
if [[ ${IMAGES_DELETED} == false ]]; then
echo "No images matching the pattern were found for deletion."
echo "No images found" > deleted_images.txt
else
echo -e "Deleted images: ${DELETED_IMAGES}"
echo "${DELETED_IMAGES}" > deleted_images.txt
fi
- name: Send Slack Notification
uses: slackapi/[email protected]
with:
payload: |
{
"text": "Docker Cleanup completed for repository: ${{ github.repository }}",
"attachments": [
{
"pretext": "Deleted Docker Images",
"color": "${{ steps.cleanup.outcome == 'success' && 'good' || 'danger' }}",
"fields": [
{
"title": "Outcome",
"value": "${{ steps.cleanup.outcome == 'success' && 'Images were deleted' || 'No images deleted' }}",
"short": true
},
{
"title": "Deleted Images",
"value": "$(cat deleted_images.txt)",
"short": false
},
]
}
]
}
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}