如何编写流水线来丢弃旧版本?

How to write Pipeline to discard old builds?

groovy 语法生成器不适用于示例步骤 properties: Set Job Properties。我选择了 Discard old builds,然后在 Max # of builds to keep 字段中输入 10,然后输入 Generate Groovy,但没有任何显示。

詹金斯版本:2.7

您可以使用 properties 方法,该方法嵌套在 BuildDiscarderProperty 中,最终具有您要设置的键。我仍然没有可靠的方法来查找每个键的正确语法。经过多次猜测和验证:

properties([[$class: 'BuildDiscarderProperty', strategy: [$class: 'LogRotator', artifactDaysToKeepStr: '', artifactNumToKeepStr: '', daysToKeepStr: '', numToKeepStr: '10']]]);

请注意,此代码段适用于脚本语法。

至于声明性语法,您可以使用 options 块:

pipeline {
  options {
    buildDiscarder(logRotator(numToKeepStr: '30', artifactNumToKeepStr: '30'))
  }
  ...
}

logRotator 的参数(来自 the source code):

  • daysToKeepStr: 历史只保留到今天
  • numToKeepStr: 仅保留此数量的构建日志。
  • artifactDaysToKeepStr: 工件只保留到今天。
  • artifactNumToKeepStr:只有这个数量的构建保留了它们的工件。

可以在 Cloudbees knowledge base and in the docs for options block 中找到更多信息。

Vadim 的回答出于某种未知原因对我不起作用。我将其简化如下,现在可以使用了:

options {
    buildDiscarder(logRotator(numToKeepStr: '3'))
}
  1. 在特定的 天后放弃构建 :

     options {
         buildDiscarder(logRotator(daysToKeepStr: '7'))
     }
    
  2. 在特定数量的 构建后丢弃构建:

     options {
         buildDiscarder(logRotator(numToKeepStr: '7'))
     }
    

如果你想在多分支管道作业级别配置构建保留(相对于所有单独的 Jenkinsfiles)这也是可能的: https://issues.jenkins-ci.org/browse/JENKINS-30519?focusedCommentId=325601&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-325601

除了 BuildRetentionBranchProperty 之外,您还可以在此处配置任何其他 *BranchPropertyhttps://github.com/jenkinsci/branch-api-plugin/tree/master/src/main/java/jenkins/branch

尽管它们可能不会显示在 GUI 中,至少对于 Jenkins 2.73.2 来说是这样。但是您仍然可以使用 JobDSL 或直接修改 config.xml(我没这么说 ;-))

Jenkins 有内置的语法生成器页面。

管道语法:片段生成器
<your jenkins url>/管道语法/

管道语法:指令生成器
<your jenkins url>/指令生成器/

Discard old builds 来自指令生成器的示例

对于脚本化管道使用:

properties([
    buildDiscarder(logRotator(daysToKeepStr: '3', numToKeepStr: '3')),
])

如果您需要一种编程方式(即从函数执行此操作,而不是使用 options{} 管道语法):

def someFunction() {
  ...
  properties([
    buildDiscarder(logRotator(numToKeepStr: '5'))
  ])
}

对于声明式管道,您可以添加:

options {

    buildDiscarder(
        logRotator(
            // number of build logs to keep
            numToKeepStr:'5',
            // history to keep in days
            daysToKeepStr: '15',
            // artifacts are kept for days
            artifactDaysToKeepStr: '15',
            // number of builds have their artifacts kept
            artifactNumToKeepStr: '5'
        )
    )
}