How to change the job template used by an instance using the Script Console?

Issue

  • As a admin, I would like to change the “Template X” (for “Template Y”) used by a “job A” Script Console

Environment

Resolution

The CloudBees Template Plugin doesn’t have a versioning mechanism and doesn’t allow to manage promotions and to incrementally apply a template change on all its instance. Because of this if you change a job template all its instances will be updated at the same time when the template is saved.

A workaround is to manually manage versions of the template by creating different copies/updates (Template_V1, Template_V2, ) and to manually attach instances from a template to another.

The following groovy script allow you to configure the existing Job JobA_FullName to use the template [template Y.getFullName][]. It must be adapted to your usecase and executed in the script console.

Script

The following script would solve the described issue.

Notes:

1) Please make a backup of your $JENKINS_HOME before running it.
2) Overall - RunScripts (admin) permission is needed in order to run it.
3) The following script has been tested in the following environment.
* CloudBees Jenkins Enterprise 2.73.1.2-rolling
* CloudBees Template plugin:4.33

import com.cloudbees.hudson.plugins.modeling.ModelList
import com.cloudbees.hudson.plugins.modeling.impl.jobTemplate.InstanceFromJobTemplate
import com.cloudbees.hudson.plugins.modeling.impl.jobTemplate.JobPropertyImpl

def jenkins = Jenkins.instance
def InstanceFromJobTemplate templateX, templateY
def TEMPLATE_Y_FullName = 'SUPPORT-Team/Templates/Template Y'
def JOB_A_FullName = 'SUPPORT-Team/Templates/Job A'

if ((ModelList.get().getItem(TEMPLATE_Y_FullName)) != null){
  templateY = new InstanceFromJobTemplate(ModelList.get().getItem(TEMPLATE_Y_FullName))
  if (jenkins.getItemByFullName(JOB_A_FullName) != null){
    def jobA = jenkins.getItemByFullName(JOB_A_FullName)
    templateX = InstanceFromJobTemplate.from(jobA)
    println "[DEBUG]: $JOB_A_FullName existing template name: $templateX.model.name"
    jobA.addProperty(new JobPropertyImpl(templateY))
    templateY.save()
    templateX = InstanceFromJobTemplate.from(jobA)
    println "[DEBUG]: $JOB_A_FullName updated template name: $templateX.model.name"
  }else {
    println "[ERROR]: $JOB_A_FullName does not exist in this instance"
  }
} else {
  println "[ERROR]: $TEMPLATE_Y_FullName does not exist in this instance"
}  

Console Output

If it succeeds:

[DEBUG]: SUPPORT-Team/Templates/Job A existing template name: Template X
[DEBUG]: SUPPORT-Team/Templates/Job A updated template name: Template Y
Have more questions? Submit a request

0 Comments

Please sign in to leave a comment.