Cloning Jenkins jobs

2022/12/19

Tags: jenkins groovy clone jobs duplicate jobs automation

This post is based on a scenario that I have on my project: I have a number of jobs in a view on Jenkins which run some CI tasks. On a new project release cycle, these jobs need to be duplicated, renamed and modified with some pattern (release version in my case).

This can be done manually, of course, if the number of jobs is small enough, but when the number gets bigger, it’s not fun anymore.

Therefore, automation is key.

Jenkins allows running Groovy scripts which can manipulate the jobs. Here is the script I came up with to make my life easier for this scenario:

import hudson.model.*
 
def str_view = "Name of the view"
def str_search = "substring of job name to search"
def str_replace = "new job substring"
 
def view = Hudson.instance.getView(str_view)
 
//copy projects of a view
for(item in view.getItems())
{
  try
  {
    if(!item.getName().find(str_search))
      continue
    
    newName = item.getName().replace(str_search, str_replace)

    // copy the job
    def job = Hudson.instance.copy(item, newName)
    job.disabled = false
    // change branch used
    scm = item.getScm()
    newBranch = scm.getBranches()[0].getName().replace("old branch prefix", "new branch prefix")
    newScm = new hudson.plugins.git.GitSCM(scm.getUserRemoteConfigs(), [new hudson.plugins.git.BranchSpec(newBranch)], scm.getBrowser(), scm.getGitTool(), scm.getExtensions())
    job.setScm(newScm)
    // change the job contents for the new release
    shell_contents = job.getBuildersList()[0].getContents()
    shell_contents = shell_contents.replace("old job command", "new job command")
    hudson.tasks.Shell newShell = new hudson.tasks.Shell(shell_contents)
    job.getBuildersList().replace(newShell)
    job.save()
    
    view.add(job)
    //disable old job
    item.disabled = true
    item.save()

    println(" $item.name copied as $newName")
  }
  catch(java.lang.IllegalArgumentException ex)
  {
    println(" $item.name was already copied, skipping")
  }

}

I leave this here so that other people might reuse, or just use it as a starting point for their own use cases. The script can be run in “Manage Jenkins” -> “Script Console”.