gitlab – How to cache maven dependencies for your .gitlab-ci.yml Gitlab builds

  devops

On the build server, the server with Gitlab on it, create the directory where to cache jars:

sudo mkdir /root/mavenrepo

If you don’t have maven, install it:

sudo apt-get update
sudo apt-get install maven

Edit your maven’s settings.xml file:

sudo nano /etc/maven/settings.xml
<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">

<localRepository>/opt/mymavenrepo</localRepository>

<pluginGroups>
</pluginGroups>
<proxies>
</proxies>
<servers>
</servers>
<mirrors>
</mirrors>
<profiles>
</profiles>
</settings>

Edit the gitlab-runner’s config.toml file:

sudo nano /etc/gitlab-runner/config.toml

and the volumes entry, which maps <gitlab server’s directories>:

concurrent = 1
check_interval = 0

[session_server]
  session_timeout = 1800

[[runners]]
  name = ""
  url = ""
  token = ""
  executor = ""

[[runners]]
  name = "webapp"
  url = "https://gitlab.myserver.example.com"
  token = "453deaa5fe42c096d7d225f4447120"
  executor = "docker"
  output_limit = 32096
  [runners.custom_build_dir]
  [runners.docker]
    tls_verify = false
    image = "alpine:latest"
    privileged = true
    disable_entrypoint_overwrite = false
    oom_kill_disable = false
    disable_cache = false
    volumes = ["/etc/maven:/root/settings", "/opt/mymavenrepo:/root/m2"]
    shm_size = 0
  [runners.cache]
    [runners.cache.s3]
    [runners.cache.gcs]

Restart the runner:

gitlab-runner restart

In the .gitlab-ci.yml file, specify -Dmaven.repo.local=/root/m2 so that the repo directory gets used with the cached files, instead of downloading them every time.

Example .gitlab-cy.yml:

image: maven:latest

services:
- docker:dind

before_script:
- whoami
- echo $CI_JOB_STAGE
- pwd

stages:
- build

maven-build:
stage: build
script:
- echo "building now"
- "$MAVEN_HOME/bin/mvn clean compile package --update-snapshots --show-version -Dmaven.repo.local=/root/m2 -Dmaven.test.skip=true"
tags:
- webapp