Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating a Jenkins job with the Groovy Jenkins API

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));
}
like image 964
Shane Gannon Avatar asked Jul 07 '15 15:07

Shane Gannon


People also ask

What is Jenkins groovy script?

Groovy is a very powerful language which offers the ability to do practically anything Java can do including: Create sub-processes and execute arbitrary commands on the Jenkins controller and agents. It can even read files in which the Jenkins controller has access to on the host (like /etc/passwd )

Does Jenkins require groovy?

Groovy scripts are not necessarily suitable for all users, so Jenkins created the Declarative pipeline. The Declarative Pipeline syntax is more stringent. It needs to use Jenkins' predefined DSL structure, which provides a simpler and more assertive syntax for writing Jenkins pipelines.


1 Answers

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

like image 166
Oliver Gondža Avatar answered Sep 28 '22 19:09

Oliver Gondža