To retrieve all the upstreamJobs
, you can utilize the getUpstreamBuilds()
method from currentBuild
. This function returns all the UpstreamBuilds
except for the last one. See the Jenkins documentation: RunWrapper.getUpstreamBuilds().
Example Scenario
Imagine you have a sequence of jobs: job1 -> job2 -> job3 -> job4. Here, calling currentBuild.getUpstreamBuilds()
from job4 will return information for [job1, job2].
def upstreamBuilds = currentBuild.getUpstreamBuilds()
upstreamBuilds.each { build ->
def upstreamProjects = build.getBuildCauses().upstreamProject
upstreamProjects.each { jobName ->
if (jobName) {
// perform some action with jobName
}
}
}
Getting Information for Previous Build Causes
To retrieve information for a previous build cause (e.g., job3), you can do the following:
def upstreamBuilds = currentBuild.getUpstreamBuilds()
String previousJobName
if (currentBuild?.getBuildCauses()?.upstreamProject?.size() > 0) {
def upstreamProjects = currentBuild.getBuildCauses().upstreamProject
upstreamProjects.each { jobName ->
if(jobName) {
// do something with jobName
}
}
}
This will store the name of job3 in previousJobName
.
Retrieve All Upstream Build Names
To collect the names of all upstream builds, you can define a function like this:
static def getAllUpstreamBuildNames() {
def upstreamBuildNames = []
def upstreamBuilds = currentBuild.getUpstreamBuilds()
if (currentBuild?.getBuildCauses()?.upstreamProject?.size() > 0) {
def upstreamProjects = currentBuild?.getBuildCauses()?.upstreamProject
upstreamProjects.each{ previousJobName ->
if (previousJobName) {
upstreamBuildNames.add(previousJobName)
}
}
}
upstreamBuilds.each { build ->
if (build?.getBuildCauses()?.upstreamProject?.size() > 0) {
def upstreamProject = build.getBuildCauses()?.upstreamProject
upstreamProject.each { jobName ->
if (jobName) {
upstreamBuildNames.add(jobName)
}
}
}
}
return upstreamBuildNames
}
At the end you will have in upstreamBuildNames
[job1,job2,job3]
Note
If you need to reference the current job (job4 in this scenario), you can directly use it since it is the context from which these methods are being called.
Hope this helps! Feel free to ask if you have further questions or need more details.