Chris F
Chris F

Reputation: 16803

Get Jenkins build number via Groovy script?

I have a Jenkins parameterized build called "deploy-job", and I use the Extensible Choice option set to System Groovy Choice Parameter. In the Groovy Script box, I have this

import hudson.model.*

BUILD_JOB_NAME = "build-multi-branch-pipeline-job"

def getJobs() {
    def hi = Hudson.instance
    return hi.getItems(Job)
}

def getBuildJob() {
    def buildJob = null
    def jobs = getJobs()
    (jobs).each { job ->
        if (job.displayName == BUILD_JOB_NAME) {
            buildJob = job
        }
    }
    return buildJob
}

def getAllBuildNumbers(Job job) {
    def buildNumbers = []
    (job.getBuilds()).each { build ->
        def status = build.getBuildStatusSummary().message
        if (status.contains("stable") || status.contains("normal")) {
          buildNumbers.add(build.BUILD_NUMBER.toString())
        }
    }
    return buildNumbers
}

def buildJob = getBuildJob()
return getAllBuildNumbers(buildJob)

However, when I run my "deploy-job", I'm NOT seeing the build numbers of "multi-branch-pipeline-job" in the choice box when I run Build with parameters, it's jub blank!

I suspect I'm not doing this call right?

buildNumbers.add(build.BUILD_NUMBER.toString())

What is the correct syntax in this case? Thanks!

Upvotes: 0

Views: 4853

Answers (1)

daggett
daggett

Reputation: 28634

1/ use try-catch to see an error in your choice. this will help you to understand the error.

def getAllBuildNumbers(Job job) {
    try {
        ...
        return buildNumbers
    }catch(Throwable t){ 
        return [t.toString()]
    }
}

2/ your answer is already there

Jenkins Plugin How to get Job information

Upvotes: 0

Related Questions