Last active
June 19, 2024 05:36
-
-
Save nieldw/7edb6685bd175393e5ef0b7c748ba6cd to your computer and use it in GitHub Desktop.
Bash script to remove old images in continuous integration (jenkins,teamcity,bamboo,etc) environment. It keeps the provided image (therefore making it available for caching), but removes all older versions of that image.
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 bash | |
usage(){ | |
# ============================================================ | |
echo This script removes all images of the same repository and | |
echo older than the provided image from the docker instance. | |
echo | |
echo This cleans up older images, but retains layers from the | |
echo provided image, which makes them available for caching. | |
echo | |
echo Usage: | |
echo | |
echo '$ ./delete-images-before.sh <image-name>:<tag>' | |
exit 1 | |
# ============================================================ | |
} | |
[[ $# -ne 1 ]] && usage | |
IMAGE=$(echo $1 | awk -F: '{ print $1 }') | |
TAG=$(echo $1 | awk -F: '{ print $2 }') | |
FOUND=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep ${IMAGE}:${TAG}) | |
if ! [[ ${FOUND} ]] | |
then | |
echo The image ${IMAGE}:${TAG} does not exist | |
exit 2 | |
fi | |
docker images --filter before=${IMAGE}:${TAG} \ | |
| grep ${IMAGE} \ | |
| awk '{ print $3 }' \ | |
| xargs --no-run-if-empty \ | |
docker --log-level=warn rmi --force || true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment