Skip to content
Martin d'Anjou edited this page Jun 6, 2018 · 2 revisions

Jenkins jobs can be created inside folders when the Folders plugin is installed. The folders plugin is installed as a default plugin on all recent versions of Jenkins.

The jenkins-rest library supports folders in all its JobsApi methods.

Working with folders is a bit awkward. In Jenkins, folders are considered to be a type of job, and require their own XML configuration file. This configuration must be provided to Jenkins, and hence to the jenkins-rest library, in order to create a folder. The easiest way to obtain an XML configuration for a folder, is to ask Jenkins for it. First manually create a folder in Jenkins, then ask for the config.xml file using curl.

For example:

curl "http://jenkins/job/folderName/config.xml" -o folder.xml

The rest of this section illustrates at a high level how to create folders using the jenkins-rest library.

First the folder.xml file is read into a string:

String folderConfig = new File("folder.xml").text

Then a folder is created by calling the JobsApi create method:

RequestStatus status = client.api().jobsApi().create(null, "folder-1", folderConfig)

The first argument to the create method is the name of the folder in which to create an item. To create an item in the root folder, simply pass null as the first argument. The second argument is the name of the item to create, and the last element is the XML configration for the item. In this case, the item is a folder, so the XML configuration is thus that of a folder.

Folders can be nested:

RequestedStatus status = client.api().jobsApi().create("folder-1", "folder-2", folderConfig)

Jobs can be created inside nested folders:

RequestedStatus status = client.api().JobsApi().create("folder-1/folder-2", "myJob", jobConfig)

Where the jobConfig is the XML configuration string of the job.

The above will result in the following URL to myJob: http://host/job/folder-1/job/folder-2/job/myJob. Note that the jenkins-rest library takes care of adding the job/ prefixes to the items, and users do not need to pass them when calling the APIs.

A complete example can be found in FolderExample.groovy.

With a live instance of Jenkins running, the example can be executed like so:

export JENKINS_REST_CREDENTIALS=user:password
export JENKINS_REST_ENDPOINT=http://localhost:8080/
groovy FolderExample.groovy
Clone this wiki locally