Jenkins – Updating a Jenkins job with the Groovy Jenkins API

apigroovyJenkins

I'm looking at using the Groovy script console to create and update jobs on Jenkins. Using the API documented here

http://javadoc.jenkins-ci.org/

I've discovered how to create a job by using
createProjectFromXML(String name, InputStream xml)

But this method will fail if the job already exists. How can I update an existing job with new xml?

Update

Based on @ogondza's answer I used the follow to create and then update a job

import jenkins.*
import jenkins.model.*
import hudson.*
import hudson.model.*
import java.io.*
import java.nio.charset.StandardCharsets
import javax.xml.transform.stream.*

config = """......My config.xml......"""

InputStream stream = new ByteArrayInputStream(config.getBytes(StandardCharsets.UTF_8));

job = Jenkins.getInstance().getItemByFullName("job_name", AbstractItem)

if (job == null) {
  println "Constructing job"
  Jenkins.getInstance().createProjectFromXML("job_name", stream);
}
else {
  println "Updating job"
  job.updateByXml(new StreamSource(stream));
}

Best Answer

Use AbstractItem#updateByXml for updating. Also note that you can create/update jobs by XML using REST API and Jenkins CLI.

Related Topic