这是一个老问题,但在 6 年后仍然有意义。 Build whenever a SNAPSHOT dependency is built 设置上有一个“阈值”字段,可以控制哪些构建将触发
来自pipeline-maven-plugin README:
基于在 Maven 中达到的Maven lifecycle phase 的阈值
上游作业的构建(打包、安装、部署)。默认情况下,仅
到达部署阶段的 Maven 构建将触发下游
构建。
例如,在脚本化管道的withMaven() 中,您可以设置pipelineGraphPublisher 和lifecycleThreshold: 'deploy',例如:
withMaven(
maven: MAVEN_VERSION,
jdk: JAVA_VERSION,
mavenOpts: MAVEN_OPTS,
globalMavenSettingsConfig: globals.MAVEN_SETTINGS_ID,
options: [
pipelineGraphPublisher(
lifecycleThreshold: 'deploy',
includeSnapshotVersions: true
)
]) {
sh("mvn ${PHASE}")
}
然后任何执行生命周期阶段的 SNAPSHOT 构建以下deploy(例如package 或install)将不会触发下游作业。请注意,deploy 已经是默认设置,因此此示例并不是特别有用,但它展示了如何使用该设置,您可能希望将其设置为另一个阶段。
第一部分已经完成,但是现在您需要一种方法来有条件地为您想要触发下游构建的构建执行不同的 Maven 生命周期阶段。您不想要触发下游构建。我们根据分支名称执行此操作,以便 Pull Request 和 Release 分支不会触发上游包:
/**
* Return the correct Maven goal for the current branch
*
* Because the pipelineGraphPublisher's lifecycleThreshold in the withMaven() call above is set to 'deploy', pipelines
* that run the 'install' goal will not trigger downstream jobs; this helps us minimize superfluous Jenkins builds:
*
* https://github.com/jenkinsci/pipeline-maven-plugin/blob/master/README.adoc#trigger-downstream-pipeline-when-a-snapshot-is-built
*/
String getGoalForCurrentBranch() {
if ( env.BRANCH_NAME ==~ /(^PR-(\d+)$)|(^releases\/v.*)/ ) {
echo("Pull Request or release branch detected! Executing Maven 'install' goal rather than 'deploy' goal to avoid triggering downstream Jenkins jobs")
return 'install'
}
return 'deploy'
}
然后,您可以在执行mvn 的任何位置调用此getGoalForCurrentBranch() 方法以确定执行哪个生命周期阶段:
withMaven(
...
sh("mvn ${getGoalForCurrentBranch()}")
)
大多数分支将执行 mvn deploy 并且将触发下游 Jenkins 作业,但 Pull Request 分支将执行 mvn install 并且不会触发下游作业。
对此的警告是,您可能还有其他依赖于某些生命周期阶段的东西。在上面的示例中,Pull Request 分支工件不会部署到您的工件存储库(例如 Nexus)。在我们的例子中,这实际上是期望的行为,但您需要确定什么是您可以接受的,并相应地调整您的阈值。