Operations 7 min read

Creating Jenkins Projects with the Core API and Job DSL via a Jenkinsfile

This article demonstrates how to use Jenkins Core API and Job DSL in a Groovy Jenkinsfile to programmatically create, update, and manage Jenkins jobs and folders, including handling security approvals and template project configuration.

DevOps Cloud Academy
DevOps Cloud Academy
DevOps Cloud Academy
Creating Jenkins Projects with the Core API and Job DSL via a Jenkinsfile

Previously we introduced using the Jenkins Core API and Job DSL to create projects, but did not explain how to use the Core API directly. This article adds a practical example that creates a Jenkins project through a Jenkinsfile, helping you become familiar with the Core API.

API Documentation

An API reference is required to use the Core API; the Javadoc can be found at https://javadoc.jenkins-ci.org/overview-summary.html .

Understanding the Requirements

In Jenkins project management we can use Folders to categorize projects belonging to different groups. A template project is created inside a folder, and subsequent projects are copied from this template. If a project already exists, its configuration is updated; otherwise the pipeline ends.

We start by locating the classes we need.

jenkins.model.Jenkins   # class used
Jenkins.instance        # obtain Jenkins instance
getItemByFullName()    # create a project instance
getItem()               # get a project (returns null if not found)
getItem("xxxx").configFile.asString().trim()   # get project config file
Jenkins.checkGoodName(name) # validate project name
createProjectFromXML() # create project via XML
updateByXml()           # update project via XML
save()                  # save project configuration

Writing the Script

import javax.xml.transform.stream.StreamSource
import jenkins.model.Jenkins

def j = Jenkins.instance
String name = "test/devops-ci"   // full project name

// If the name contains '/', the part before '/' is a folder
if (name.contains('/')) {
    println(name.tokenize('/')[0])
    j = j.getItemByFullName(name.tokenize('/')[0])   // check if folder exists
    println(j)
    name = name.tokenize('/')[ -1]
    println(name)
}

// Get the configuration XML of the template project (ensure it exists)
xml = j.getItem("test-devops-service").configFile.asString().trim()

Jenkins.checkGoodName(name)
println(name)

if (j.getItem(name) == null) {
    println "Created job \"${name}\"."
    j.createProjectFromXML(name, new ByteArrayInputStream(xml.getBytes()))
    j.save()
} else if (j.getItem(name).configFile.asString().trim() != xml.trim()) {
    j.getItem(name).updateByXml(new StreamSource(new ByteArrayInputStream(xml.getBytes())))
    j.getItem(name).save()
    println "Job \"${name}\" already exists.  Updated using XML."
} else {
    println "Nothing changed.  Job \"${name}\" already exists."
}

Running and Debugging

During debugging many security restrictions may block the required methods; you need to approve them. The $JENKINS_HOME/scriptApproval.xml file should contain the following signatures (copy them and restart Jenkins):

<approvedSignatures>
    <string>method hudson.XmlFile asString</string>
    <string>method hudson.model.AbstractItem getConfigFile</string>
    <string>method hudson.model.AbstractItem updateByXml javax.xml.transform.stream.StreamSource</string>
    <string>method hudson.model.ItemGroup getItem java.lang.String</string>
    <string>method hudson.model.Saveable save</string>
    <string>method java.lang.String getBytes</string>
    <string>method jenkins.model.Jenkins getItemByFullName java.lang.String</string>
    <string>method jenkins.model.ModifiableTopLevelItemGroup createProjectFromXML java.lang.String java.io.InputStream</string>
    <string>new java.io.ByteArrayInputStream byte[]</string>
    <string>new javax.xml.transform.stream.StreamSource java.io.InputStream</string>
    <string>staticMethod jenkins.model.Jenkins checkGoodName java.lang.String</string>
    <string>staticMethod jenkins.model.Jenkins getInstance</string>
</approvedSignatures>

Conclusion

Using the Core API is not the only way to create Jenkins projects, but it enables you to write Groovy scripts for initial Jenkins configuration such as creating credentials, installing plugins, and more, which is a necessary step in stateless Jenkins research.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

ci/cdAutomationGroovyJenkinsCore APIJob DSL
DevOps Cloud Academy
Written by

DevOps Cloud Academy

Exploring industry DevOps practices and technical expertise.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.