Installing Maven automatically to Jenkins when it is running in Docker

Default featured post

Installing Maven automatically to Jenkins when it is running in Docker. In the last article, we discussed how to add credentials to Jenkins when building it from a Docker file. In this article, we discuss Maven automatic installation. As we discuss in the previous article, when building Jenkins Docker container, we can automate our Jenkins configuration in two ways.

The first approach is using Jenkins Configuration as code plugin to do some configuration in a set of YAML file. The second approach is to write Groovy scripts and copying them over to the container while building it. So that Jenkins pick the scripts and executes them automatically.

In the ideal world, we would like to move away from the second approach and only rely on Jenkins Configuration as code plugin to do everything. However, the plugin still lacks in some area and automatic Maven installation is one of them. And to work around that, we have to rely on a Groovy script.

import hudson.tasks.Maven.MavenInstallation;
import hudson.tools.InstallSourceProperty;
import hudson.tools.ToolProperty;
import hudson.tools.ToolPropertyDescriptor;
import hudson.util.DescribableList;

def mavenDesc = jenkins.model.Jenkins.instance.getExtensionList(hudson.tasks.Maven.DescriptorImpl.class)[0]

def isp = new InstallSourceProperty()
def autoInstaller = new hudson.tasks.Maven.MavenInstaller("3.5.3")
isp.installers.add(autoInstaller)

def proplist = new DescribableList<ToolProperty<?>, ToolPropertyDescriptor>()
proplist.add(isp)

def installation = new MavenInstallation("M3", "", proplist)

mavenDesc.setInstallations(installation)
mavenDesc.save()

The process is straightforward. We just need to create a Groovy script under our /grrovy directory or create one if doesn’t exist. And code the script like this:

import hudson.tasks.Maven.MavenInstallation;
import hudson.tools.InstallSourceProperty;
import hudson.tools.ToolProperty;
import hudson.tools.ToolPropertyDescriptor;
import hudson.util.DescribableList;

def mavenDesc = jenkins.model.Jenkins.instance.getExtensionList(hudson.tasks.Maven.DescriptorImpl.class)[0]

def isp = new InstallSourceProperty()
def autoInstaller = new hudson.tasks.Maven.MavenInstaller("3.5.3")
isp.installers.add(autoInstaller)

def proplist = new DescribableList<ToolProperty<?>, ToolPropertyDescriptor>()
proplist.add(isp)

def installation = new MavenInstallation("M3", "", proplist)

mavenDesc.setInstallations(installation)
mavenDesc.save()

Lastly, we have to make sure that the files are copied to Jenkins init.groovy.d/ when it is built. To do so, need to add this line to our Dockerfile:

COPY groovy/* /usr/share/jenkins/ref/init.groovy.d/

That’s all. As you have seen the process is quite easy despite not being able to automatically install Maven using the configuration as code plugin.