Code-your-life DevOps Jenkins

Reloading a single job in Jenkins

September 8, 2018

Here is how you reload a single job in Jenkins without restarting or reloading the complete configuration, with the use of Groovy. You can easily modify the script to reload two or all Jenkins jobs without restarting.

This can be helpful for all those, luckily, rare occasions where Jenkins decides to forget the configuration or at least parts of the configuration for a given job(s)

Jenkins allows running the script in the UI or via the CLI.

UI

To use the UI copy the following script in your Jenkins Script page, for instance, https://github.com/jesstruck/jenkinsMaintinance

import java.io.InputStream;
import java.io.FileInputStream
import java.io.File;
import javax.xml.transform.stream.StreamSource

def hudson = hudson.model.Hudson.instance;

//to get a single job
//def job = hudson.model.Hudson.instance.getItem('my-job');

for(job in hudson.model.Hudson.instance.items) {   

    if (job.name == "my-job") {

        def configXMLFile = job.getConfigFile();
        def file = configXMLFile.getFile();

        InputStream is = new FileInputStream(file);

        job.updateByXml(new StreamSource(is));
        job.save();         
    }      
} 

CLI

to Run the script via the CLI copy the script above into a file called reload-job.groovy

java -jar jenkins-cli.jar  reload-job.groovy

Alternatively use the interactive shell

java -jar jenkins-cli.jar groovysh

For authentication when using the CLI please see https://www.jenkins.io/doc/book/managing/cli/