在库中使用Jenkins管道,但添加其他阶段

时间:2019-05-22 20:54:27

标签: jenkins groovy jenkins-pipeline

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

project-a / Jenkinsfile

library 'the-shared-library'

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

共享库/vars/buildProject.groovy

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

我们希望扩展此功能,以允许在管道中为某些项目(例如,许多项目中的1个)执行额外的阶段。我正在考虑这样做,如果可能的话:

  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

共享库/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
  }
}

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

1 个答案:

答案 0 :(得分:0)

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

//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?