Skip to content

Instantly share code, notes, and snippets.

@clcollins
Created September 15, 2016 19:32
Show Gist options
  • Save clcollins/a7dcb7b0830cee42ca849341a3aec177 to your computer and use it in GitHub Desktop.
Save clcollins/a7dcb7b0830cee42ca849341a3aec177 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Script that can be run to cleanup a Jenkins slave server that's used to build docker images
# Tries to account for the fact that a job might be running and using images & containers
# Adjust the Docker command to match your environment (esp. the $HOST hostname)
# TLS included as script it designed to be run from the master
DOCKER_TLS_VERIFY=1
DOCKER="docker --tlscacert /ca.pem --tlscert /cert.pem --tlskey /key.pem -H ${HOST}"
RUNNING_CONTAINERS=$($DOCKER ps -q)
# Gotta wait until the slave quiets down
until [[ -z $RUNNING_CONTAINERS ]]
do
echo "Still busy..."
sleep 15
RUNNING_CONTAINERS=$($DOCKER ps -q)
done
# Get all these at once in case another run starts
CONTAINERS=$($DOCKER ps -aq)
ORPHAN_IMAGES=$($DOCKER images | grep \<none\> |awk '{print $3}') # Cannot remove orphans by name (since they don't have one)
IMAGES=$($DOCKER images | grep -v \<none\> | tail -n +2 | awk '{ print $1 ":" $2}' ) # Can't use -q here, as rmi doesn't like tagged images
if [[ ! -z $CONTAINERS ]]
then
$DOCKER rm $CONTAINERS
fi
if [[ ! -z $ORPHAN_IMAGES ]] || [[ ! -z $IMAGES ]]
then
$DOCKER rmi $ORPHAN_IMAGES $IMAGES
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment