Issue
I use Jenkins job DSL script to create other jobs. Now I want to have a separate script that will enable/disable the jobs that I created by the DSL script.
Here is my enable/disable script:
job("cronjob/${JOB_TYPE}_${ENVRIONMENT}_CRONJOB") {
if ( ACTION == "enable" ) {
disabled(false)
} else if ( ACTION == "disable" ) {
disabled(true)
}
}
It does enable/disable the job. But it also empties the job which has the SCM, schedule and parameters setup.
How do I enable/disable an existing job in Jenkins w/o losing the job? Not manually!
Thanks!
Solution
You can use the followig script to do this.
def jobToDisable = "Sample"
Jenkins.instance.getAllItems(Job.class).each { jobitem ->
def jobName = jobitem.name
def jobInfo = Jenkins.instance.getItem(jobName)
if(jobName.equals(jobToDisable)) {
jobInfo.setDisabled(true) // false to enable
}
}
Full pipeline
node {
stage('Stage one') {
script {
disableJob("folder1/Sample3")
}
}
stage('Final Step') {
echo "Result"
}
}
def disableJob(name) {
def jobToDisable = name
Jenkins.instance.getAllItems(Job.class).each { jobitem ->
def jobName = jobitem.getFullName()
def jobInfo = Jenkins.instance.getItemByFullName(jobName)
if(jobName.equals(jobToDisable)) {
println("Disabling Job!!")
jobInfo.setDisabled(true)
}
}
}
Answered By - ycr
Answer Checked By - Robin (JavaFixing Admin)