Skip to content

Instantly share code, notes, and snippets.

@mmaassen
Created March 6, 2015 09:48
Show Gist options
  • Save mmaassen/17960f72025745750e6a to your computer and use it in GitHub Desktop.
Save mmaassen/17960f72025745750e6a to your computer and use it in GitHub Desktop.
Script to cleanup jenkins build
#!/bin/bash
## How many builds do you want to keep
KEEP_LAST_BUILDS=5
if [[ $# -lt 2 ]]; then
echo "Usage: $(basename $0) 'url' 'project name'"
echo "Example: $(basename $0) 'http://jenkins.example.com' 'example'"
exit 1
fi
## Read Arguments
JENKINS_URL="$1"
PROJECT="${2// /%20}" # Replace space by %20
## Find Available builds
BUILDS=$(curl -s "$JENKINS_URL/job/$PROJECT/" | grep "Last build" | grep -Eo '#[0-9]{1,10}' | sort| uniq | awk -F'#' '{print $2}'| sed -e ':a' -e 'N' -e '$!ba' -e 's/\n/ /g')
## Echo
echo "[>] Project: $PROJECT"
echo "[>] Url: $JENKINS_URL/job/$PROJECT/"
echo "[>] Builds: $BUILDS"
##
LIMIT=0
for build in ${BUILDS[@]}; do
let LIMIT=LIMIT+1
done
echo "[>] Amount: $LIMIT"
if [[ $LIMIT > $KEEP_LAST_BUILDS ]]; then
LIMIT=$(($LIMIT - $KEEP_LAST_BUILDS))
i=0
for build in ${BUILDS[@]}; do
if [[ $i < $LIMIT ]]; then
echo "[$build] doDelete"
if curl -X POST "$JENKINS_URL/job/$PROJECT/$build/doDelete" >/dev/null 2>&1 ; then
echo " [>] success"
else
echo " [!] failed"
fi
else
echo "[$build] keep"
fi
let i=i+1
done
fi
echo "[>] Script done"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment