How to build a Jenkins job from pipeline ignoring if the job doesn't exist?

走远了吗. 提交于 2020-01-16 04:02:07

问题


I'm trying to build a job from my Jenkins pipeline like this:

 build job:"${jobName}", propagate:false, wait:false

Here ${jobName} is a multi branch pipeline job and as such may sometimes not exist in my workflow.

This step marks my build as failed if the job doesn't exist. Is there a way to simply ignore and move on if the job doesn't exist?

I tried to check whether the given job exist or not like this:

    if(jenkins.model.Jenkins.instance.getItem("${jobName}") != null) {
        println("Preparing to build the ${jobName}...")
        build job:"${jobName}", propagate:false, wait:false
    } else {
        println("Not building the job ${jobName} as it doesn't exist")
    }

However, this at times fails (due to script security?). Is there a better way of doing this? All I need is to build a job only if it exists.


回答1:


If you use a scripted pipeline, you can add a try-catch block:

try {
    println("Preparing to build the ${jobName}...")
    build job:"${jobName}", propagate:false, wait:false
} catch (NullPointerException e) {
    println("Not building the job ${jobName} as it doesn't exist")
}


来源:https://stackoverflow.com/questions/52054417/how-to-build-a-jenkins-job-from-pipeline-ignoring-if-the-job-doesnt-exist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!