Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JenkinsFile how to query if job exists

In a declarative Jenkinsfile how can you determine if a job exists?

I want to conditionally run a stage if another job exists, like so:

pipeline {
  agent { label 'mylabel' }
  // Run the the stages:
  stages {
    stage('Pre-Build') {
      steps {
        timestamps { ansiColor('xterm') { sh 'build/jenkins_prebuild.sh' } }
      }
    }
    stage('Pre-Build') {
      steps {
        timestamps { ansiColor('xterm') { sh 'build/jenkins_build.sh' } }
      }
    }
    stage('Trigger Remote If Exists'){
    when { JOB_EXISTS }
      steps {
        timestamps {
          ansiColor('xterm') {
            sh 'build/pre-trigger.sh'
            build job: "../myjob/foo", wait: false, parameters: [booleanParam(name: 'FOO', value: true)]
          }
        }
      }
    }
  }
}

Basically, what should I do for JOB_EXISTS?

like image 704
grayaii Avatar asked Oct 20 '25 09:10

grayaii


1 Answers

if (jenkins.model.Jenkins.instance.getItem("YOUR_JOB_NAME") != null) {

}

You may not be able to use the above snippet in your declarative pipeline. But you should be able to use this in a global shared lib.

UPDATE: An administrator needs to approve this snippet in "Manage Jenkins -> In-process Script Approval" section.

like image 172
James Selvakumar Avatar answered Oct 22 '25 05:10

James Selvakumar