Maven cache in GitLab CI that actually hits
GitLab can only cache paths inside the project directory, and Maven keeps its repository in the home directory. So by default nothing is cached and every job downloads the internet.
variables:
MAVEN_OPTS: "-Dmaven.repo.local=$CI_PROJECT_DIR/.m2/repository"
cache:
key:
files:
- pom.xml
paths:
- .m2/repository
build:
stage: build
script:
- mvn -B verify
Keying on pom.xml gives a new cache only when dependencies change. For multi-module projects list the parent pom; GitLab accepts at most two files in the key.
On jobs that only read the cache, add policy: pull so they do not spend time uploading it back unchanged.