52

I delete old jenkins builds with rm where job is hosted:

my_job/builds/$ rm -rf [1-9]*

These old builds are still visible in job page. How to remove them with command line?
(without the delete button in each build user interface)

Philippe Blayo
  • 10,610
  • 14
  • 48
  • 65
  • Not an answer: but useful, if you have groovy : https://github.com/jenkinsci/jenkins-scripts/blob/master/scriptler/discardOldBuilds.groovy – Jayan Mar 22 '16 at 14:05

12 Answers12

56

Here is another option: delete the builds remotely with cURL. (Replace the beginning of the URLs with whatever you use to access Jenkins with your browser.)

$ curl -X POST http://jenkins-host.tld:8080/jenkins/job/myJob/[1-56]/doDeleteAll

The above deletes build #1 to #56 for job myJob.

If authentication is enabled on the Jenkins instance, a user name and API token must be provided like this:

$ curl -u userName:apiToken -X POST http://jenkins-host.tld:8080/jenkins/job/myJob/[1-56]/doDeleteAll

The API token must be fetched from the /me/configure page in Jenkins. Just click on the "Show API Token..." button to display both the user name and the API token.

Edit: As pointed out by yegeniy in a comment below, one might have to replace doDeleteAll by doDelete in the URLs above to make this work, depending on the configuration.

Erwan Legrand
  • 4,148
  • 26
  • 26
  • 13
    I had to use `doDelete` instead of `doDeleteAll`. Might not be at the correct version of Jenkins. – yegeniy Aug 04 '14 at 15:38
  • Is this an old feature or a new feature? It's not available in 1.556. – greggles Mar 06 '15 at 16:18
  • 1
    @greggles This is weird, it is still here in version 1.580.1. Possibly you have enabled authentication on your Jenkins instance. I'll update my answer to explain how to deal with authentication. – Erwan Legrand Mar 11 '15 at 16:26
  • `curl -u userName:apiToken -X GET JENKINSURL/job/JobName/doDelete` to delete via job name – Joviano Dias Aug 17 '15 at 14:59
  • As of Jenkins version 1.626, I couldn't get this to work. Kept giving me 404s. However the accepted answer (CIGuy) does. – Dark Star1 Nov 09 '15 at 08:42
  • @DarkStar1 I tried Jenkins 1.636 just now. I had to use `doDelete` instead of `doDeleteAll` as suggested in a comment above by yegeniy. – Erwan Legrand Nov 09 '15 at 10:46
  • I get the following error - `--_curl_--http://jenkins-host.tld:8080/jenkins/job/myJob/40/doDeleteAll curl: (6) Could not resolve host: jenkins-host.tld` and if I change it to `localhost:8080` I get 404 – Amos Bordowitz Jan 13 '16 at 10:14
  • 1
    @AmosBordowitz Probably jenkins is not accessible as /jenkins in your case. What is the URL you use to access Jenkins with your browser? – Erwan Legrand Jan 15 '16 at 15:59
  • @ErwanLegrand you're right. Problem solved! Thanks :) – Amos Bordowitz Jan 17 '16 at 08:42
43

It looks like this has been added to the CLI, or is at least being worked on: http://jenkins.361315.n4.nabble.com/How-to-purge-old-builds-td385290.html

Syntax would be something like this: java -jar jenkins-cli.jar -s http://my.jenkins.host delete-builds myproject '1-7499' --username $user --password $password

CIGuy
  • 5,076
  • 28
  • 37
  • 14
    You didn't mention where to get `jenkins-cli.jar`: Your Jenkins install will tell you where on this page: `http://localhost:8080/cli/`. – Ben Dec 20 '13 at 20:57
  • whaere should i install the jar file ? – Alex Brodov Sep 18 '14 at 16:46
  • The jar must not be installed. Just place it somewhere on your file system and enter the command with the full path (or enter the command in that directory). – Clerenz Jun 08 '15 at 15:35
  • 1
    Actually this syntax worked for me: `java -jar jenkins-cli.jar -s http://jenkins.url -auth user:pass delete-builds folder/project '350-375'` – Serge Apr 30 '20 at 06:58
28
  1. Check your home jenkins directory:
    • "Manage Jenkins" ==> "Configure System" enter image description here
    • Check field "Home directory" (usually it is /var/lib/jenkins)

Command for delete all jenkins job builds

/jenkins_home/jobs> rm -rf */builds/*
  1. After delete should reload config:

    • "Manage Jenkins" ==> "Reload Configuration from Disk"

enter image description here

0x8BADF00D
  • 7,138
  • 2
  • 41
  • 34
qxo
  • 1,584
  • 15
  • 11
  • I wasn't able to get the cURL or jar solutions working, and this seemed like a good solution for simply removing the build logs. Long story short, some passwords were leaked in my logs and I just needed to do some cleanup. This method does, however, leave other records of the build intact, e.g. on the job screen itself. In my case I didn't really care. – killthrush Oct 20 '15 at 17:59
13

You can do it by Groovy Scripts using Hudson API.. Access your jenkins instalation

http://localhost:38080/script.

For Example, for deleting all old builds of all projects using the follow script: Note: Take care if you use Finger Prints , you will lose all history.

import hudson.model.*
// For each project
for(item in Hudson.instance.items) {
  // check that job is not building
  if(!item.isBuilding()) {
    System.out.println("Deleting all builds of job "+item.name)
    for(build in item.getBuilds()){
      build.delete()
    }  
  }
  else {
    System.out.println("Skipping job "+item.name+", currently building")
  }
}

Or for cleaning all workspaces :

import hudson.model.*
// For each project
for(item in Hudson.instance.items) {
  // check that job is not building
  if(!item.isBuilding()) {
    println("Wiping out workspace of job "+item.name)
    item.doDoWipeOutWorkspace()
  }
  else {
    println("Skipping job "+item.name+", currently building")
  }
}

There are a lot of examples on the Jenkins wiki

Software Engineer
  • 15,457
  • 7
  • 74
  • 102
Eduardo Fabricio
  • 2,151
  • 2
  • 25
  • 32
  • How can i delete a few builds lets say 1-10 in specific build, and where can i find the documentation for using the hudson package – Alex Brodov Sep 18 '14 at 17:05
  • 1
    Current implementation will not work within folders. You would need to do Hudson.instance.getAllItems(AbstractProject.class) to get all Projects. – Steve Sep 26 '14 at 18:56
10

Is there a reason you need to do this manually instead of letting Jenkins delete old builds for you?

You can change your job configuration to automatically delete old builds, based either on number of days or number of builds. No more worrying about it or having to keep track, Jenkins just does it for you.

Dennis S.
  • 2,081
  • 14
  • 14
  • 10
    I've found this to be useful when you're creating a project and you get several failures before it is set up correctly. After it's done, I wanted to clear old wrong builds because they end up being just noise – Bruno Lopes Feb 01 '13 at 16:04
  • 1
    Where is this option? I cant find it in my version of Jenkins - 1.5. – ziggy Apr 04 '14 at 19:01
  • 2
    It's in the configuration for each job. Select the Discard Old Builds checkbox, and options become available to control how old builds are deleted. – Dennis S. Apr 04 '14 at 19:34
  • @ziggy you can't find it because it's a plugin that needs installing first https://wiki.jenkins-ci.org/display/JENKINS/Discard+Old+Build+plugin – Anentropic Feb 09 '16 at 11:21
  • I wanted to use this feature """change your job configuration to automatically delete old builds""" . But it is not working. I have it set and there are thousands of old build kept. – Russell Lego Aug 24 '18 at 19:31
  • @Anentropic is there a specific link to a version of that plugin that works? I can't get it (or "Enhanced Old Build Discarder") to install or work correctly as of today. I found the git source of the plugin you're talking about which says updates were made relatively recently but there are no releases or plugin zips to download there. – Christopher Aug 19 '20 at 12:57
2

From Script Console Run this, but you need to change the job name:

def jobName = "name"
def job = Jenkins.instance.getItem(jobName)
job.getBuilds().each { it.delete() }
job.nextBuildNumber = 1
job.save()
Nael Marwan
  • 1,030
  • 1
  • 13
  • 32
1

The following script cleans old builds of jobs. You should reload config from disk if you delete build manually:

import hudson.model.*

for(item in Hudson.instance.items) {
    if (!item.isBuilding()) {
        println("Deleting old builds of job " + item.name)
        for (build in item.getBuilds()) {
            //delete all except the last
            if (build.getNumber() < item.getLastBuild().getNumber()) {
                println "delete " + build
                try {
                    build.delete()
                } catch (Exception e) {
                    println e
                }
            }
        }
    } else {
        println("Skipping job " + item.name + ", currently building")
    }
}
David Rawson
  • 20,912
  • 7
  • 88
  • 124
  • 1
    add explanation to your answer as well. – jack jay Feb 05 '17 at 10:53
  • For some jobs I get `groovy.lang.MissingMethodException: No signature of method: com.cloudbees.hudson.plugins.folder.Folder.isBuilding() is applicable for argument types: () values: []` – carl verbiest Aug 08 '19 at 15:11
0

From Jenkins Scriptler console run the following Groovy script to delete all the builds of jobs listed under a view:

import jenkins.model.Jenkins

hudson.model.Hudson.instance.getView('<ViewName>').items.each() {
    println it.fullDisplayName


    def jobname = it.fullDisplayName
    def item = hudson.model.Hudson.instance.getItem(jobname)
    def build = item.getLastBuild()
    if (item.getLastBuild() != null) {
        Jenkins.instance.getItemByFullName(jobname).builds.findAll {
            it.number <= build.getNumber()
        }.each {
            it.delete()
        }

    }
}
David Rawson
  • 20,912
  • 7
  • 88
  • 124
Manoj
  • 11
  • 3
0
def jobName = "MY_JOB_NAME"
def job = Jenkins.instance.getItem(jobName)
job.getBuilds().findAll { it.number < 10 }.each { it.delete() }

if you had 12 builds this would clear out builds 0-9 and you'd have 12,11,10 remaining. Just drop in the script console

JeffCharter
  • 1,431
  • 17
  • 27
0

This script will configure the build retention settings of all of the Jenkins jobs.

Change the values from 30 and 200 to suite you needs, run the script, then restart the Jenkins service.

#!/bin/bash

cd $HOME
for xml in $(find jobs -name config.xml)
do
    sed -i 's#<daysToKeep>.*#<daysToKeep>30</daysToKeep>#' $xml
    sed -i 's#<numToKeep>.*#<numToKeep>200</numToKeep>#' $xml
done
AAber
  • 1,562
  • 10
  • 14
0

The script below works well with Folders and Multibranch Pipelines. It preserves only 10 last builds for each job. That could be adjusted or removed (proper if) if needed. Run that from web script console (example URL: https://jenkins.company.com/script)

def jobs = Hudson.instance.getAllItems(hudson.model.Job.class)
for (job in jobs){
    println(job)

    def recent = job.builds.limit(10)
    for(build in job.builds){
        if(!recent.contains(build)){
            println("\t Deleting build: " + build)
            build.delete()
        }
    }
}
michal-michalak
  • 827
  • 10
  • 6
0

From my opinion all those answers are not sufficient, you have to do:

echo "Cleaning:"
echo "${params.PL_JOB_NAME}"
echo "${params.PL_BUILD_NUMBER}"

build_number = params.PL_BUILD_NUMBER as Integer
sleep time: 5, unit: 'SECONDS'

wfjob = Jenkins.instance.getItemByFullName(params.PL_JOB_NAME)
wfjob.getBuilds().findAll { it.number >= build_number }.each { it.delete() }
wfjob.save()
wfjob.nextBuildNumber = build_number
wfjob.save()
wfjob.updateNextBuildNumber(build_number)
wfjob.save()
wfjob.doReload()

Or the job will not be correctly reset and you have to hit build until you reach next free number in the meanwhile the jenkins log will show:

java.lang.IllegalStateException: JENKINS-23152:  ****/<BUILD_NUMBER> already existed; 
Nikolai Ehrhardt
  • 570
  • 4
  • 14