Paul
Paul

Reputation: 367

Getting error while deleting Jenkins build history

Hello All I am getting below error while deleting build history of jenkins jobs

No build logs found in  calcmanager-pull-request and build history count is : 0
[Pipeline] End of Pipeline
java.lang.NullPointerException: Cannot invoke method getLastBuild() on null object

Below is the pipeline script I am using. calcmanager-pull-request job contains build history but it is displaying as zero

pipeline {
    agent { label 'master' }
    stages {
        stage('delete all jobs build history'){

        steps {
            script {
               def buildLogCount=10
Jenkins.instance.getAllItems(Job.class).each { jobitem ->
           def jobName = jobitem.name
           def jobInfo = Jenkins.instance.getItem(jobName)

          if(jobInfo.getLastBuild()){

                def lastBuildNum=jobInfo.getLastBuild().getNumber()

              if(lastBuildNum>=buildLogCount){
                 def deletedBuildNum=lastBuildNum - buildLogCount
                    def deletedNumRange = Fingerprint.RangeSet.fromString("0-${deletedBuildNum}",false);

                    def buildCount=jobInfo.getBuilds(deletedNumRange).size()

                    if(buildCount==0){
                        println "No build logs found in  ${jobName} and build history count is : ${buildCount}"
                    }
                    else{

                        jobInfo.getBuilds(deletedNumRange).each { item ->
                             item.delete()
                        }
                    }
                }
                else{
                  println "No build logs to delete in ${jobName}"
                }
            }
          else{

            println "No build logs found in ${jobName}"
            }
}
            }
            }
            }
        }
    }
}

Upvotes: 0

Views: 342

Answers (2)

Paul
Paul

Reputation: 367

Above code works fine if you don't have any multi branch pipeline jobs. If you have multibranch pipeline jobs then use below code in jenkins file.

       properties(
        [
    buildDiscarder(logRotator(daysToKeepStr: '60', numToKeepStr: '7')),
        ]
                  )

Upvotes: 0

max.ivanch
max.ivanch

Reputation: 349

You got that error due to some of jobs was never run. It doesn't have history.

So you can build a List with jobs with history:

Jenkins.instance.getAllItems(Job.class)
.findAll { it.getLastBuild()?.getNumber() } // if job doesn't not history it will return null == false
.each { job ->
   def lastBuildNum=job.getLastBuild().getNumber()
   /// you code is here
}

Upvotes: 1

Related Questions