You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jenkins 2.309环境下如何获取最后一次成功构建的编号?

Troubleshooting: Can't Retrieve Last Successful Build Number in Jenkins 2.309

I’ve run into similar head-scratching issues with Jenkins build metadata before, so let’s break down why your scripts are returning null even when successful builds exist, and fix this step by step.

Common Causes & Practical Fixes

1. Incorrect Job Reference (Folders Are the #1 Culprit!)

If your job is nested inside a folder, Jenkins.instance.getItem('jobName') won’t locate it—this method only searches for top-level jobs. You need to use the full job path with getItemByFullName() instead:

catchError { 
    script { 
        def fullJobName = "demo-spring-boot" // Update to "folderName/demo-spring-boot" if using folders
        def job = Jenkins.instance.getItemByFullName(fullJobName)
        
        if (!job) {
            println "Job not found! Double-check the full path (including parent folders)"
            return
        }

        def lastSuccessBuild = job.lastSuccessfulBuild
        if (lastSuccessBuild) {
            println "Last successful build number: ${lastSuccessBuild.number}"
        } else {
            println "Still no build found—let’s check permissions next!"
        }
    } 
}

2. Permission or Script Approval Restrictions

Jenkins 2.x enforces strict security controls that block certain method calls unless explicitly approved:

  • If running in the Script Console: Head to Manage Jenkins > In-process Script Approval and approve any pending signatures for methods like getItemByFullName() or lastSuccessfulBuild.
  • If running in a Pipeline: Ensure the user/agent executing the Pipeline has Overall/Read and Job/Read permissions for the target job.

3. Fixing the /api/xml Issue

You might have been hitting the wrong API endpoint. Instead of the root /api/xml, use the job-specific API with a targeted query:

  • For XML: http://your-jenkins/job/demo-spring-boot/api/xml?xpath=/*/lastSuccessfulBuild/number
  • For JSON (easier to parse): http://your-jenkins/job/demo-spring-boot/api/json?tree=lastSuccessfulBuild[number]

4. Edge Case: Multibranch Pipelines

If demo-spring-boot is a Multibranch Pipeline job, you need to target the specific branch instead of the parent job:

def job = Jenkins.instance.getItemByFullName('demo-spring-boot/main') // Replace 'main' with your actual branch name

Quick Sanity Check

Before running any script, confirm the job’s full path by looking at your browser’s URL bar when on the job page. If it shows jenkins/job/my-folder/job/demo-spring-boot/, your full job name is my-folder/demo-spring-boot.

内容的提问来源于stack exchange,提问作者user630702

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 15:57:43