Jenkins 脚本命令行应用总结

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()
}

 4 total views,  1 views today

页面下部广告