在 Jenkins 管道脚本中运行
build(job: 'path/to/job')
会以阻塞方式触发提供的 @job
,即它触发构建并等待其完成并返回 RunWrapper
对象。
设置 wait: false
不会等待,但也不会返回任何内容,因此我没有任何对触发构建的引用。
有没有办法异步触发构建并且知道触发了哪些构建?
如果您不等待构建,构建步骤不会返回任何内容的原因是,构建可能会卡在队列中(因此没有构建号),或者只是卡在某种不支持构建的状态中。不允许快速获取构建 ID。
您可以通过自己实现逻辑来克服这个问题。例如,假设您愿意等到作业开始,您可以创建如下所示的函数:
def getTriggeredBuild(job) {
// Run while the job did not start
while (true) {
// Search for the current build as the cause trigger
def message = "upstream project \"${JOB_NAME}\" build number ${BUILD_NUMBER}"
for (build in Jenkins.instance.getItem(job).getBuilds()) {
// Iterate over all builds and find the one that was triggred by this build
if(build.getCauses().any{ it.getShortDescription().contains(message) }) {
return build
}
}
sleep 5
}
}
此函数可以驻留在共享库中,使其可用于所有管道,也可以驻留在 Jenkinsfile 中,但管理员必须批准某些函数的使用(共享库中不需要)。
使用将直接进行:
pipeline {
agent any
stages {
stage('Hello') {
steps {
script {
def jobName = 'triggred_job'
build job: jobName, wait: false
// Get the build that was triggered
def build = getTriggeredBuild(jobName)
println(build.number)
}
}
}
}
}
该功能的等待逻辑可以根据您的需求进行修改。