How to change a job template instance parameter using the Script Console?

Article ID:211943748
1 minute readKnowledge base

Issue

  • As a Jenkins admin, I have a job template (named Template X) with a parameter Prop X. From this template I create a job instance (named Job A) with the value aaa for Prop X. I want to replace aaa by bbb using a script.

Environment

  • CloudBees Jenkins Enterprise - Managed controller (CJEMM)

  • CloudBees Jenkins Template Plugin

Resolution

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.

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 JOB_A_FullName = 'SUPPORT-Team/Templates/Job A'
def PROP_2_UPDATE = 'Prop X'
def InstanceFromJobTemplate templateX = null

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"
    if (templateX.getValue(PROP_2_UPDATE)!=null){
       println "[DEBUG]: $PROP_2_UPDATE existing value: " + templateX.getValue(PROP_2_UPDATE)
       templateX.setValue(PROP_2_UPDATE,"bbb")
       templateX.save()
       println "[DEBUG]: $PROP_2_UPDATE new value: " + templateX.getValue(PROP_2_UPDATE)
    } else {
       println "[ERROR]: $PROP_2_UPDATE has not been assigned OR does not exist"
    }
  }else {
    println "[ERROR]: $JOB_A_FullName does not exist in this instance"
}

Console Output

If it succeeds:

[DEBUG]: SUPPORT-Team/Templates/Job A existing template name: Template X
[DEBUG]: Prop X existing value: aaa
[DEBUG]: Prop X new value: bbb

Tested product/plugin versions

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