template-create-job-groovy

Article ID:217142568
1 minute readKnowledge base

Issue

I am trying to create a new job based off of a template in Jenkins using the template plugin but I could not find any example.

Environment

  • CloudBees Jenkins Enterprise > 1.596.1.1

  • Jenkins LTS > 1.596.1

  • Jenkins > 1.600

  • CloudBees Template plugin > 4.16

Resolution

This is a very simple example to create a job from template with a parameter.

import com.cloudbees.hudson.plugins.modeling.impl.entity.EntityInstance;
import com.cloudbees.hudson.plugins.modeling.impl.entity.EntityModel;

Jenkins j = Jenkins.getInstance()

Item template = j.getItemByFullName('WebSphere/Template_Job_WAS_EAR_Deploy')
ModifiableTopLevelItemGroup folder = j.getItemByFullName('WebSphere')

Job newJob = folder.createProject(template.asDescriptor(), "new-job-name9", true)

if(newJob != null ){
    println newJob.getName()
    newTemplateInstance = EntityInstance.from(newJob)
    newTemplateInstance.setValue('otherAttr','value')
    newTemplateInstance.save()
} else {
    println 'Could not create template or it do not exists'
}