In Jenkins I have one pipeline triggering another pipeline through the use of "build job" syntax:
Inside the Upstream_Job.groovy
def build_result = build job: "Downstream_Job", parameters: [
[$class: "StringParameterValue", name: "param1", value: var1],
[$class: "StringParameterValue", name: "param2", value: var2],
]
I wish to obtain the name Upstream_Job
info inside the Downstream_Job
without explicitly passing as a parameter.
Setting in Upstream_Job.groovy
env.CURRENT_JOB_NAME = "Upstream_Job";
However I would get null when I try to print this env.CURRENT_JOB_NAME
in the downstream job.
However, the scope of env in one job is typically not extended to the scope of another job.
Even though Jenkins' pipeline syntax doc says:
These definitions will also be available via the REST API during the build or after its completion, and from upstream Pipeline builds using the build step.
for env
.
It does not have to be set as env
, as long as I can know the name Upstream_Job
that invokes the Downstream_Job
. It can be put in currentBuild
if that can be retrieved by the Downstream_Job
.
You can access build causes through the currentBuild
variable:
script {
print currentBuild.getBuildCauses('org.jenkinsci.plugins.workflow.support.steps.build.BuildUpstreamCause')[0]?.upstreamProject
}
getBuildCauses
returns a filtered list of your build causes, which can be long if it's a timer triggering a job that is triggering another job, for example. In this case you are only interested in the first parent workflow.
The list can be empty if there are no workflows in your build causes, for example if you trigger it manually, so [0]
would return null
and we need a safe navigation ?.
operator there.