Advertisement
Guest User

Untitled

a guest
May 18th, 2018
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Groovy 2.26 KB | None | 0 0
  1. // Clone all the jobs from a view (branch) to another view (branch,
  2. // performing all the required modifications.
  3. // Requires:
  4. //  - Both source and target views to exist an be configured below.
  5. //  - New runner, versions... to be already available
  6.  
  7. import org.jenkinsci.plugins.workflow.job.WorkflowJob
  8. import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition
  9.  
  10. // Configuration section.
  11.  
  12. // View names.
  13. def sourceViewName = 'B - master'
  14. def targetViewName = 'B - 35'
  15.  
  16. // Prefix to use in the names of the new jobs.
  17. def targetPrefix   = '35'
  18.  
  19. // Filter, in case we want to restrict to some job(s). Blank = no filter
  20. def filter = 'W.01.01'
  21.  
  22.  
  23. // End of configuration section.
  24.  
  25. // Verify views exist.
  26. def sourceView = Jenkins.instance.getView(sourceViewName)
  27. if (sourceView == null) {
  28.   println('Configuration error: sourceViewName view does not exist')
  29.   return
  30. }
  31. def targetView = Jenkins.instance.getView(targetViewName)
  32. if (targetView == null) {
  33.   println('Configuration error: targetViewName view does not exist')
  34.   return
  35. }
  36.  
  37. // Iterate over all the projects in the source view.
  38. for (item in sourceView.getItems()) {
  39.   def name = item.getName()
  40.   println('Processing "' + name + '"')
  41.  
  42.   // Apply filter if existing.
  43.   if (filter != '' && !name.contains(filter)) {
  44.     println('  Skipped, does not match "' + filter + "'")
  45.     continue
  46.   }
  47.  
  48.   // Calculate new name and verify the job doesn't exist.
  49.   def newName = name.substring(0,1) + targetPrefix + name.substring(1)
  50.   if (Jenkins.instance.getItem(newName)) {
  51.     println('  Skipped, already exits "' + newName + '"')
  52.     continue
  53.   }
  54.   println ('  Creating new job "' + newName + "'")
  55.  
  56.   // Copy, disable and save.
  57.   def job = Jenkins.instance.copy(item, newName)
  58.   job.disabled = true
  59.   println ('    Job duplicated')
  60.  
  61.   // Apply pipeline replacements
  62.   if (job.class.simpleName == 'WorkflowJob') {
  63.     def script = job.getDefinition().getScript()
  64.     // Master() by prefix()
  65.     def search = 'Master()'
  66.     def replacement = 'M' + targetPrefix + '()'
  67.     script = script.replace(search, replacement)
  68.     job.setDefinition(new CpsFlowDefinition(script))
  69.     println ('    Script adapted: "' + search + '" => "' + replacement + '"')
  70.    
  71.   }
  72.  
  73.   // Save the job
  74.   job.save()
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement