Check whether image is in use by hash

this seems sometimes to be required as the Docker daemon looses the
reference and does not display the name in `docker ps -a` output...

Signed-off-by: Knut Ahlers <knut@ahlers.me>
This commit is contained in:
Knut Ahlers 2018-07-08 21:31:43 +02:00
parent e5bf6c53af
commit 6924335526
Signed by: luzifer
GPG key ID: DC2729FDD34BE99E
2 changed files with 14 additions and 6 deletions

View file

@ -4,7 +4,8 @@ RUN set -ex \
&& apk --no-cache add \ && apk --no-cache add \
bash \ bash \
docker \ docker \
gawk gawk \
jq
COPY docker-clean /usr/local/bin/ COPY docker-clean /usr/local/bin/

View file

@ -2,9 +2,9 @@
set -euo pipefail set -euo pipefail
if [ -e "${HOME}/bin/script_framework.sh" ]; then if [ -e "${HOME}/bin/script_framework.sh" ]; then
source "${HOME}/bin/script_framework.sh" source "${HOME}/bin/script_framework.sh"
else else
function step() { echo $@; } function step() { echo $@; }
fi fi
step "Removing containers created / exited >= ~1h ago..." step "Removing containers created / exited >= ~1h ago..."
@ -14,9 +14,16 @@ CONTAINERS=$(docker ps -a | gawk '/(hours?|days?|weeks?|months?) ago\s+(Created|
step "Untagging all images not used by containers..." step "Untagging all images not used by containers..."
PS_OUTPUT=$(docker ps -a) PS_OUTPUT=$(docker ps -a)
for img in $(docker images | gawk '/^[a-z].*(hours?|days?|weeks?|months?) ago/{ print $1":"$2 }' | grep -v '<none>' | sort | uniq); do for img in $(docker images | gawk '/^[a-z].*(hours?|days?|weeks?|months?) ago/{ print $1":"$2 }' | grep -v '<none>' | sort | uniq); do
if ! (echo "${PS_OUTPUT}" | grep -q "\s${img}\s") && ! (echo "${PS_OUTPUT}" | grep -q "\s${img%:latest}\s"); then imghash=$(docker inspect "${img}" | jq -r '.[0].Id' | sed -E 's/^sha256:(.{12}).*/\1/')
docker rmi --no-prune "${img}"
fi # Check if image is currently active
(echo "${PS_OUTPUT}" | grep -q "\s${img}\s") && continue
# Check if image with stripped ":latest" is currently active
(echo "${PS_OUTPUT}" | grep -q "\s${img%:latest}\s") && continue
# Check if image hash is currently active (sometimes docker looses named references)
(echo "${PS_OUTPUT}" | grep -q "\s${imghash}\s") && continue
docker rmi --no-prune "${img}"
done done
step "Removing dangling images..." step "Removing dangling images..."