如何在Jenkins声明式管道中的多个节点上运行相同的阶段? [英] How do I run the same stages on multiple nodes in Jenkins declarative pipeline?
问题描述
我们有一个这样的管道:
We have a pipeline like this:
pipeline {
agent none
stages {
stage('Build') {
// ...
}
stage('Test') {
parallel {
stage('Test on Debian') {
agent {
label 'debian'
}
steps {
unstash 'compile-artifacts'
unstash 'dot-gradle'
sh './gradlew check --stacktrace'
}
post {
always {
junit '*/build/test-results/**/*.xml'
}
}
}
stage('Test on CentOS') {
agent {
label 'centos'
}
steps {
unstash 'compile-artifacts'
unstash 'dot-gradle'
sh './gradlew check --stacktrace'
}
post {
always {
junit '*/build/test-results/**/*.xml'
}
}
}
stage('Test on Windows') {
agent {
label 'windows'
}
steps {
unstash 'compile-artifacts'
unstash 'dot-gradle'
bat "gradlew.bat check --stacktrace"
}
post {
always {
junit '*/build/test-results/**/*.xml'
}
}
}
stage('Test on macOS') {
agent {
label 'macos'
}
steps {
unstash 'compile-artifacts'
unstash 'dot-gradle'
sh './gradlew check --stacktrace'
}
post {
always {
junit '*/build/test-results/**/*.xml'
}
}
}
}
}
}
}
每个阶段基本上都是相同的,除了Windows块中我已经知道如何处理的一行之外,是否有办法对这些阶段的公共部分进行模板化以消除重复?
Every stage is essentially identical, save for one line in the Windows block which I already know how to deal with, so is there a way to template out the common parts of these stages to remove the duplication?
我已经尝试过将循环内联,但这不是声明性管道允许您执行的操作. :(
I already tried putting a loop inline, but it's not something that declarative pipelines let you do. :(
推荐答案
您可以使用常规方法重构step{}
-blocks:
You can refactor your step{}
-blocks with groovy-methods:
def stageX(boolean linux) {
unstash 'compile-artifacts'
unstash 'dot-gradle'
if (linux) {
sh './gradlew check --stacktrace' }
else {
bat "gradlew.bat check --stacktrace" }
}
您必须像在step{}
中那样调用它:
which you have to call like the following in your step{}
:
steps {
script { stageX( true) } // or with false for your windows agent
}
当然,您可以对junit-plugin-call进行相同的操作:
Of course you can do the same for your junit-plugin-call:
def junitCall() {
junit '*/build/test-results/**/*.xml'
}
并这样称呼它:
post {
always {
script { junitCall()
}
}
}
您不会赢得很多行,但是它将大大改善代码的处理.如果您想进一步清理Jenkinsfile,可以将这些方法放入您导入的共享库中,这样就不会在您的Jenkinsfile中声明它们.
You won't win a lot of lines but it will improve the handling of the code a lot. If you want to cleanup your Jenkinsfile even more you could put the methods into a shared-library which you import so they aren't even declared in your Jenkinsfile.
这篇关于如何在Jenkins声明式管道中的多个节点上运行相同的阶段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!