首页 > 解决方案 > 删除 Jenkins 构建历史时出错

问题描述

大家好,我在删除詹金斯作业的构建历史时遇到错误

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

下面是我正在使用的管道脚本。calcmanager-pull-request 作业包含构建历史记录,但显示为零

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}"
            }
}
            }
            }
            }
        }
    }
}

标签: jenkinsgroovyjenkins-pipeline

解决方案


由于某些作业从未运行,您收到了该错误。它没有历史。

因此,您可以使用具有历史记录的作业构建一个列表:

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
}

推荐阅读