Updating a Jenkins Job Using the Groovy Jenkins API

I am looking for a Groovy script console to create and update jobs on Jenkins. Using the API registered here

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

I discovered how to create a task using   createProjectFromXML(String name, InputStream xml)

But this method will not succeed if the work already exists. How to update an existing job using the new xml?

Update

Based on @ogondza's answer, I used the following to create and then update the task

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));
}
+4
source share
1 answer

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

+3
source

All Articles