Skip to content

Instantly share code, notes, and snippets.

@AATHITH
Created February 19, 2023 11:03
Show Gist options
  • Save AATHITH/5b7015405de80c5324513d5e8dd8c295 to your computer and use it in GitHub Desktop.
Save AATHITH/5b7015405de80c5324513d5e8dd8c295 to your computer and use it in GitHub Desktop.
Copy all Jobs from a view into another view | Jenkins
// Get the original view
def originalView = jenkins.model.Jenkins.instance.getView("Old-View-Name")
// Set the new view name
def newViewName = "New-View-Name"
// Check if the new view already exists
def newView = jenkins.model.Jenkins.instance.getView(newViewName)
if (newView == null) {
// If the new view does not exist, create a new ListView
newView = new hudson.model.ListView(newViewName)
// Add the new view to Jenkins
jenkins.model.Jenkins.instance.addView(newView)
}
// Loop through all jobs in the original view
for (job in originalView.getItems()) {
// Create a new job name by adding a prefix to the original job name or else it will throw "job already exist" error
def job_name = "Copy-" + job.getName()
if (jenkins.model.Jenkins.instance.getJob(job_name) == null) {
// If the job does not exist, create a new job by copying the original job and setting the new job name
def newJob = job.getParent().copy(job, job_name)
// Add the new job to the new view
newView.add(newJob)
// Print a message indicating that the job was created and added to the new view
println("Job ${newJob.getName()} created and added to ${newViewName}")
} else {
// If the job already exists, get the existing job and add it to the new view
def existingJob = jenkins.model.Jenkins.instance.getJob(job_name)
newView.add(existingJob)
// Print a message indicating that the existing job was added to the new view
println("Job ${existingJob.getName()} already exists and added to ${newViewName}")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment