你好,我在删除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}"
}
}
}
}
}
}
}
}
答案 0 :(得分:1)
由于某些作业从未运行,您得到了该错误。没有历史。
因此,您可以使用具有历史记录的作业来构建列表:
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
}
答案 1 :(得分:0)
如果您没有任何多分支管道作业,则上述代码可以正常工作。如果您有多分支管道作业,请在jenkins文件中使用以下代码。
properties(
[
buildDiscarder(logRotator(daysToKeepStr: '60', numToKeepStr: '7')),
]
)