如何在本地覆盖 Jenkinsfile 库函数?

How to override a Jenkinsfile library function locally?

我有一个在许多项目中使用的标准化声明式 Jenkinsfile。我已将整个管道移动到一个库中,因此我的 Jenkinsfile 如下所示:

@Library('default_jenkins_libs') _
default_pipeline();

图书馆(var/default_pipeline.groovy):

def call() {
pipeline {
  node { <snip> }
  stages {
    stage('Lint and style') {
      steps {
      //stuff
      }
    }
    //etc...
    stage('Post-build') {
      steps {
        PostBuildStep();
      }
    }
  }
}

def PostBuildStep() {
  echo 'Running default post-build step';
}

我希望能够向 Jenkinsfile 中的实际管道代码添加定义,如下所示:

@Library('default_jenkins_libs') _

def PostBuildStep() {
  echo 'Running customized post-build step'
  //do custom stuff
}

default_pipeline();

我还不知道该怎么做。我怀疑这可能是通过库调用由 Jenkinsfile 表示的对象并调用它的 "PostBuildStep()" 来实现的,可能像 'parent.PostBuildStep()" 但我没有 class structure/naming参考。

有什么建议吗?底线是,我想要一个标准化的管道,它可以通过库更改来整体更改,但仍然可以对使用它的作业进行一些控制。

TIA

您不能覆盖在库脚本中定义的函数。但是您可以考虑将自定义 post 构建步骤定义为传递给 default_pipeline() 的闭包。考虑以下示例:

vars/default_pipeline.groovy

def call(body = null) {
    pipeline {
        agent any
        stages {
            stage('Build') {
                steps {
                    script {
                        body != null ? body() : PostBuildStep()
                    }
                }
            }
        }
    }
}

def PostBuildStep() {
    echo 'Running default post-build step';
}

詹金斯文件

@Library('default_jenkins_libs') _

default_pipeline({
    echo 'Running customized post-build step'
})

在这种情况下,default_pipeline 有一个可选参数,它是一个定义自定义 post 构建步骤的闭包。 运行 以下示例将产生以下输出:

[Pipeline] node
Running on Jenkins in /var/jenkins_home/workspace/test-pipeline
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Build)
[Pipeline] script
[Pipeline] {
[Pipeline] echo
Running customized post-build step
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

希望对您有所帮助。

事实上,可以使用共享库中的全局变量覆盖管道步骤,例如将其命名为 stage.groovy

请看我在这里给出的详细答案: 以及 GitHub.

中的示例