Jenkins指令碼命令列應用總結
測試環境
Jenkins 2.304
指令碼命令列入口
Jenkins主頁→系統管理→指令碼命令列
遍歷專案
例子:獲取所有自由風格專案及相關專案資訊
def projects = Jenkins.instance.projects.collect { it } // 獲取自由風格的所有專案,注意,只能獲取自由風格專案
println(projects) // 輸出:[hudson.model.FreeStyleProject@4b8b02d[AutoTest-OMG], hudson.model.FreeStyleProject@2b953627[AutoTest-QDD],...,]
for(def project : projects) {
println(project.name) // 獲取專案名稱
println(project.getBuilds()) // 獲取構建記錄,輸出:[AutoTest-OMG #190, AutoTest-OMG #189, ...,]
println(job.nextBuildNumber) // 獲取下一次構建號,形如:256
}
遍歷Job
def jobNames = Jenkins.instance.getJobNames()
for (def jobName : jobNames) {
println(jobName) // 注意:如果是多分支專案,則輸出名稱為fullName,形如:alpha-Deployer/vip
}
批量刪除Jenkins 專案構建記錄
例子:刪除所有Job最後5次構建之前的所有歷史構建記錄,即僅保留最近5次構建記錄
def jobNames = Jenkins.instance.getJobNames()
for (def jobName : jobNames) {
def job = Jenkins.instance.getItemByFullName(jobName)
job.getBuilds().findAll { it.number < job.nextBuildNumber - 5 }.each { it.delete() }
}
例子:刪除FREE-STYLE-PROJECT專案構建號大於10的構建記錄
def projectName = "FREE-STYLE-PROJECT" // 專案名稱
def project = Jenkins.instance.getItem(projectName)
project.getBuilds().findAll { it.number > 10 }.each { it.delete() }
非多分支專案
例子:刪除FREE-STYLE-PROJECT專案的所有構建記錄
def jobName = "FREE-STYLE-PROJECT" // 專案名稱
def job = Jenkins.instance.getItem(jobName) // 本行程式碼也可以使用 def job = Jenkins.instance.getItemByFullName(jobName) 替代
println(job.getClass()) // 輸出:org.jenkinsci.plugins.workflow.job.WorkflowJob
println(job.getBuilds().getClass()) // 輸出:class hudson.util.RunList
job.getBuilds().each { println(it.getClass()) } // 輸出:class org.jenkinsci.plugins.workflow.job.WorkflowRun
job.getBuilds().each { it.delete() } // 刪除所有構建記錄
多分支專案
例子:刪除CI-Builder專案,omg job的所有構建記錄
def jobName = "CI-Builder/omg"
def job = Jenkins.instance.getItemByFullName(jobName)
job.getBuilds().each { it.delete() }
例子:刪除CI-Builder專案,所有job的所有構建記錄,並重置每個job的下次構建號為1
def projectName = "CI-Builder"
def project = Jenkins.instance.getItem(projectName)
def jobs = project.getItems().each {
def job = it
job.getBuilds().each {
it.delete()
}
job.nextBuildNumber = 1
job.save()
}