Remove Old Job Builds on Jenkins with Groovy Script

Purpose

This article describes a way to use a Groovy script to remove old builds from all jobs up to a set number. In other words, you set how many of the latest builds to keep and run it on the Jenkins Master to cleanup all previous builds for all jobs. This script includes Cloudbees Folders, Basic Projects, Github Organizations plugin and Workflow Multibranch plugin support.

Take the following script and either run it from the CLI or from the Jenkins Management Script Console GUI.

Prerequisites

Jenkins 2.x+

Steps Using GUI

Set the 2nd argument to how many builds you wish to keep. In this example all but 10 builds will be deleted for each job. listJobObjects(item, 10, 0)

Select Manage Jenkins on the Master you wish to perform the task on

Select Script Console

Paste the Groovy Script in the script window

Select Run

Steps for CLI

First you have to have a SSH Key pair setup for a user that has adiquite permissions

Generate SSH Key pair

ssh-keygen-t rsa -b4096

Add public key to local admin Jenkins user

Browse People | <username> | Configure

Paste Public key in SSH Public Keys window and Save

Copy the groovy script content to a file such as /tmp/remove-old-builds.groovy

Copy private RSA key if not already on the system i.e. ~/.ssh/id_rsa

Set permissions on the private key if needed

chmod 0400 ~/.ssh/id_rsa

Locate the jenkins-cli.jar

find . -type f -name'jenkins-cli.jar'

OR

updatedb&&locate'jenkins-cli.jar'

Run java jenkins cli from Master or you could setup another box with the jar etc.