【问题标题】:Use Jenkins pipeline in library, but add additional stage在库中使用 Jenkins 管道,但添加额外的阶段
【发布时间】:2019-05-22 20:54:27
【问题描述】:

我们有很多很多项目,它们都有自己的 Jenkinsfile,它只是执行我们共享库中定义的管道。该管道可确保以完全相同的方式构建、打包和安装所有项目。

project-a/Jenkinsfile

library 'the-shared-library'

buildProject name: 'project-a', buildApi: true, ...

the-shared-library/vars/buildProject.groovy

def call(Map config) {
  pipeline {
    // standard stages go here
  }
}

我们希望对此进行扩展,以允许在流水线中针对某些项目(例如众多项目中的一个)执行额外的阶段。如果可能的话,我正在考虑这样做:

  1. 将一个配置参数传递给buildProject
  2. buildProject.call 中,如果提供了自定义阶段,请将其附加到管道的末尾,或者可能在两个(已知)阶段之间,然后运行它

类似这样的...

project-a/Jenkinsfile

library 'the-shared-library'

def myCustomStage = ... // not sure how

buildProject name: 'project-a', buildApi: true, ..., customStage: myCustomStage

the-shared-library/vars/buildProject.groovy

def call(Map config) {
  def customStage = config.customStage

  pipeline {
    // standard stages 1 through 3
    // if customStage provided, it goes here
    // standard stages 5 through 5
  }
}

我不确定这里的正确解决方案是什么。

【问题讨论】:

  • 问题是您已经尝试过但它不起作用,还是您不知道这是否是正确的方法?如果是后者,请考虑在管道中间有条件地注入自定义阶段将破坏您从确保 all projects are built, packaged, and installed in the same exact way. 获得的任何舒适感
  • 这不是关于舒适,而是关于维护。我不想用相同的管道维护 20 个 Jenkinsfile,所以我们有一个它们都直接使用。问题是“我该怎么做”——我什至不确定如何以一种可行的方式实现它。
  • 明白了。 customStage 必须是动态的吗?也就是说,projectAcustomStage 可能与 projectB 不同吗?
  • 只要你恰当地处理customStage == null 似乎没问题。您可能还可以在这里为有趣的自定义阶段通过对象延迟/屈服做一些聪明的事情。
  • 是的,自定义阶段将在项目的 Jenkinsfile 中定义并传递到共享管道中。对于给定的项目,它要么 a) 根本不存在,要么 b) 存在并且对该项目是唯一的。

标签: jenkins groovy jenkins-pipeline


【解决方案1】:

我还没有测试过,但是这样的东西看起来应该可以工作:

//project-a/Jenkinsfile
library 'the-shared-library'

def myCustomStage = { echo 'Hello' }

buildProject name: 'project-a', buildApi: true, ..., myCustomStage
//the-shared-library/vars/buildProject.groovy
def call(Map config, Closure customStage=null) {
  def customStage = config.customStage

  pipeline {
    // standard stages 1 through 3
    // if customStage provided, it goes here
    stage('Conditional'){
      when{
        expression { customStage }
      }
      steps { script {customStage()} }
    // standard stages 5 through 5
  }
}

Can I use a Closure to define a stage in a Jenkins Declarative Pipeline?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-02
    • 2019-09-02
    • 2020-05-17
    • 1970-01-01
    相关资源
    最近更新 更多