dsl 插件删除作业时删除工作区

Delete workspace when job is removed by dsl plugin

我正在使用 jenkins dsl 插件为项目的所有分支生成 jenkins 作业。删除分支时,dsl 插件也会删除相应的 jenkins 作业。

然而,问题是工作区没有与作业一起删除,所以它们最终弄乱了我的磁盘。我发现的一种解决方案是定期列出所有工作区并检查是否存在同名的 jenkins 作业。

我想知道是否有更优雅的解决方案来自动删除刚刚被 dsl 插件删除的 jenkins 作业的过时工作区。

我的解决方案是添加另一个运行 Groovy 系统脚本的作业,该脚本清除所有不再存在或已被禁用的作业的工作区,并在 DLS 作业之后触发。

  1. 安装 Jenkins Groovy plugin
  2. 创建自由式作业
  3. 勾选构建触发器 "Build after other projects are built",并将您的 DSL 作业设置为 "Project to watch"
  4. 添加 "Execute Groovy system script" 构建步骤,将 Groovy 脚本作为 "Groovy command"。

我使用以下脚本,基于this one from this answer

import hudson.FilePath
import jenkins.model.Jenkins
import hudson.model.Job

def deleteUnusedWorkspace(FilePath root, String path) {
  root.list().sort{child->child.name}.each { child ->
    String fullName = path + child.name

    def item = Jenkins.instance.getItemByFullName(fullName);

    if (item.class.canonicalName == 'com.cloudbees.hudson.plugins.folder.Folder') {
      deleteUnusedWorkspace(root.child(child.name), "$fullName/")
    } else if (item == null) {
      println "Deleting (no such job): '$fullName'"
      child.deleteRecursive()
    } else if (item instanceof Job && !item.isBuildable()) {
      println "Deleting (job disabled): '$fullName'"
      child.deleteRecursive()
    } else {
      println "Leaving: '$fullName'"
    }
  }
}

for (node in Jenkins.instance.nodes) {
  println "Processing $node.displayName"
  def workspaceRoot = node.rootPath.child("workspace");
  deleteUnusedWorkspace(workspaceRoot, "")
}

这假设您不使用自定义工作区。