Scripted Pipeline 中如何正确设置并行构建的 stage 名称?

公孙宇阳 阅读 63

我在 Jenkins 的 Scripted Pipeline 里用 parallel 做并行任务,但每个分支的 stage 名字都显示成 “Branch A”、”Branch B” 这种默认名,想自定义成更有意义的名字,比如 “Build Frontend” 和 “Run Tests”,但改了之后 pipeline 就报错说 stage 名称无效,是不是写法有问题?

我试过这样写:

parallel(
  "Build Frontend": {
    stage("Build Frontend") {
      sh 'npm run build'
    }
  },
  "Run Tests": {
    stage("Run Tests") {
      sh 'npm test'
    }
  }
)
我来解答 赞 9 收藏
二维码
手机扫码查看
2 条解答
诸葛篷璐
在 Jenkins Scripted Pipeline 里用 parallel 来实现并行构建的时候,确实可以自定义每个分支的 stage 名称,不过你的写法有点小问题。让我详细说说怎么正确设置。

首先,在 parallel 块中,key 就是你要显示的 stage 名称,而 value 是一个闭包(closure),这个闭包里面就直接放你要执行的任务逻辑,不需要再用 stage 块去包裹。这里需要注意,stage 块在 scripted pipeline 里和 declarative pipeline 里的用法是有区别的,不能直接套用。

正确的写法应该是这样:

parallel(
"Build Frontend": {
// 这里直接写任务内容,不用再套 stage
sh 'npm run build'
},
"Run Tests": {
sh 'npm test'
}
)


原理其实很简单,parallel 方法会根据你传入的 map 来创建并行的分支,map 的 key 就是这个分支的名字,value 是要执行的逻辑。这样做不仅能让你的 pipeline 结构更清晰,而且在 Jenkins 界面上也能看到更有意义的阶段名称。

再来个实际例子看看:
// 定义并行任务
parallel(
"Compile Project": {
// 编译项目
sh 'mvn clean compile'
},
"Check Code Quality": {
// 检查代码质量
sh 'sonar-scanner'
}
)


我之前也在这里栽过跟头,以为 stage 是必需的,结果发现根本不需要在 parallel 里再套一层。希望这些能帮你解决问题。如果还有问题的话,随时问吧。
点赞
2026-03-30 09:06
a'ゞ雨路
问题在于你在 parallel 里嵌套了 stage,Jenkins Pipeline 不支持这种写法。直接在 parallel 里定义 stage 即可。代码如下:
pre class="pure-highlightjs line-numbers">parallel(
"Build Frontend": {
sh 'npm run build'
},
"Run Tests": {
sh 'npm test'
}
)
点赞
2026-03-22 23:00