Mik*_*nek 6 groovy declarative jenkins
我有一个在许多项目中使用的标准化声明性 Jenkinsfile。我已将整个管道移动到一个库中,因此我的 Jenkinsfile 如下所示:
@Library('default_jenkins_libs') _
default_pipeline();
Run Code Online (Sandbox Code Playgroud)
库(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';
}
Run Code Online (Sandbox Code Playgroud)
我希望能够向 Jenkinsfile 中的实际管道代码添加定义,如下所示:
@Library('default_jenkins_libs') _
def PostBuildStep() {
echo 'Running customized post-build step'
//do custom stuff
}
default_pipeline();
Run Code Online (Sandbox Code Playgroud)
我一直无法弄清楚如何做到这一点。我怀疑这可以通过库调用 Jenkinsfile 表示的对象并调用它的“PostBuildStep()”来实现,可能像“parent.PostBuildStep()”,但我没有类结构/命名参考。
有什么建议?最重要的是,我想要一个标准化的管道,它可以通过库的更改来整体更改,但仍然可以对使用它的作业进行一些控制。
TIA
您无法覆盖库脚本中定义的函数。但是您可以考虑将自定义构建后步骤定义为传递给 的闭包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';
}
Run Code Online (Sandbox Code Playgroud)
詹金斯文件
@Library('default_jenkins_libs') _
default_pipeline({
echo 'Running customized post-build step'
})
Run Code Online (Sandbox Code Playgroud)
在这种情况下,default_pipeline有一个可选参数,它是一个定义您的自定义构建后步骤的闭包。运行以下示例将产生以下输出:
[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
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你。