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 Approvaland approve any pending signatures for methods likegetItemByFullName()orlastSuccessfulBuild. - If running in a Pipeline: Ensure the user/agent executing the Pipeline has
Overall/ReadandJob/Readpermissions 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

