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

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

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.
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 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
Have more questions? Submit a request

0 Comments

Please sign in to leave a comment.