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

Article ID:208833668
2 minute readKnowledge base


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


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.


The following script would solve the described issue.


1) Please make a backup of your $JENKINS_HOME before running it. 2) Overall - RunScripts (admin) permission is needed in order to run it.

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: $"
    jobA.addProperty(new JobPropertyImpl(templateY))
    templateX = InstanceFromJobTemplate.from(jobA)
    println "[DEBUG]: $JOB_A_FullName updated template 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

Tested product/plugin versions

The latest update of this article has been tested and verified with: