13

I am using jenkins pipeline 2.0, and I would like to get another job's latest successful build number.

What's the pipeline syntax to use?

daspilker
  • 8,154
  • 1
  • 35
  • 49
王子1986
  • 3,019
  • 4
  • 31
  • 43

4 Answers4

26

You can get it this way

def buildNumber = Jenkins.instance.getItem('jobName').lastSuccessfulBuild.number

If you get a RejectedAccessException you will have to approve those methods, see In-process Script Approval

Vitalii Vitrenko
  • 9,763
  • 4
  • 43
  • 62
  • 1
    Is there some docu for the field `lastSuccessfulBuild`? Couldn't find any mention in Jenkins' official API docs. – Florian Jan 31 '19 at 11:34
  • 2
    @Florian here you go [Job#getLastSuccessfulBuild](https://javadoc.jenkins-ci.org/hudson/model/Job.html#getLastSuccessfulBuild--). It's actually a method but groovy allows it to be invoked in field-like way. – Vitalii Vitrenko Jan 31 '19 at 13:38
  • 2
    Consider using `getItemByFullName()` instead of `getItem()`. This can be important if you have folders and the `jobName` is in another folder. – Adrian W Mar 16 '22 at 22:27
9

To add to Vitalii's answer, this is in case you're using Multibranch Pipeline Plugin:

def buildNumber = Jenkins.instance.getItem('jobName').getItem('branchName').lastSuccessfulBuild.number
Florian Lauck
  • 321
  • 2
  • 3
7

It's so annoying to get approvals in enterprise environment(a lot of request and approvals) So I am using following API way to get the latest build number.

import groovy.json.JsonSlurperClassic
httpRequest url: 'https://jenkinsurl.local/job/Build/api/json', outputFile: 'output.json'

def jsonFile = readFile(file: 'output.json')
def data = new JsonSlurperClassic().parseText(jsonFile)
latestBuildNumber = "${data.lastSuccessfulBuild.number}"
王子1986
  • 3,019
  • 4
  • 31
  • 43
0
def build_job = build job: "Build"
build_job_number = build_job.getNumber()
hryamzik
  • 849
  • 1
  • 9
  • 16
  • 1
    That's going to build the job name specified as "Build" and then get that build number, which isn't what the OP is asking. – Michael Nov 20 '19 at 18:22