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));
}
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 )
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.
Use AbstractItem#updateByXml for updating. Also note that you can create/update jobs by XML using REST API and Jenkins CLI.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With