如何在Jenkins流水线Groovy脚本中检测Artifactory触发构建原因?
Detect Jenkins Build Triggered by Artifactory Plugin
刚好之前我也折腾过Jenkins里Artifactory插件触发的构建原因检测,结合你已经掌握的其他触发类型的检测逻辑,其实写法非常类似——不过要注意类的包路径,你之前预想的包名不对,Artifactory的触发Cause类不在hudson.triggers下面,而是属于JFrog的专属包。
核心检测代码
直接用这段代码就能检测Artifactory插件触发的构建:
// Check if the build was triggered by Artifactory Plugin artifactoryCause = upStreamBuild.getCause(org.jfrog.hudson.trigger.ArtifactoryTriggerCause) if (artifactoryCause != null) { return artifactoryCause.getShortDescription() }
整合到你的现有逻辑里
把上面的代码插入到你已有的检测流程中,完整的示例如下:
//Check if the build was triggered by SCM change scmCause = upStreamBuild.getCause(hudson.triggers.SCMTrigger.SCMTriggerCause) if (scmCause != null) { return scmCause.getShortDescription() } //Check if the build was triggered by timer timerCause = upStreamBuild.getCause(hudson.triggers.TimerTrigger.TimerTriggerCause) if (timerCause != null) { return timerCause.getShortDescription() } //Check if the build was triggered by Artifactory Plugin artifactoryCause = upStreamBuild.getCause(org.jfrog.hudson.trigger.ArtifactoryTriggerCause) if (artifactoryCause != null) { return artifactoryCause.getShortDescription() } //Check if the build was triggered by some jenkins project(job) upstreamcause = upStreamBuild.getCause(hudson.model.Cause.UpstreamCause.class) if (upstreamcause != null) { job = Jenkins.getInstance().getItemByFullName(upstreamcause.getUpstreamProject(), hudson.model.Job.class) if (job != null) { upstream = job.getBuildByNumber(upstreamcause.getUpstreamBuild()) if (upstream != null) { return upstream } } } return;
额外注意点
- 确保你的Jenkins已经安装了Artifactory插件,否则这个
org.jfrog.hudson.trigger.ArtifactoryTriggerCause类会找不到,导致检测失败。 - 如果是在Pipeline脚本中使用,要确认脚本的权限足够访问这个第三方插件的类,避免出现权限相关的报错。
内容的提问来源于stack exchange,提问作者best answer
相关产品推荐
相关产品推荐

