Pipeline code to get Jenkins job's build number?

I know that a Jenkins job's job number is just an environment variable, so if I'm writing pipeline code it'll be simply

def jobNumber = env.BUILD_NUMBER

However, if I have 2 jobs where job2 requires job1's build number, how would I do it? Here's some sample/pesudo code.

// Set the current build's display name to the Gradle artifact version
dir(workSpace) {
  // Execute a Gradle task that gets the artifact version, e.g., 1.2.3
  currentBuild.displayName = sh(script: "./gradlew printVersion",
                                returnStdout: true).trim()

So if one looks at job1's page, the left pane will have the various Gradle versions that it built instead of the typical #BUILD_NUMBER.


Now I want job2 to parse job1's builds to get the build number associated with version 1.2.3. How can I do that? Thanks.


  • While the code by @chris will do the job, the build can be achieved in a more Groovy way using the following shortened syntax:

    // If version is not an exact match you can use: it.displayName.contains('gradle_version')
    def buildNumber = Jenkins.instance.getItem('job_name').builds.find{it.displayName == 'gradle_version'}.number

    If you are not sure the version exists, you can use the following:

    def build = Jenkins.instance.getItem('job_name').builds.find {it.displayName == 'gradle_version'}
    assert build : "A build matching version gradle_version was not found"
    def buildNumber = build.number

    Something to notice is that the find method will return the first option that matches the condition, in this case it is the latest build that has the matching Gradle version.
    In case you need something different than the latest matching version you can use the findAll method to get all matching builds and than choose the relevant one based on the desired logic.