Skip to content
Latchkey

How to Cache Gradle Dependencies in a Jenkins Pipeline

Jenkins caches Gradle by pinning GRADLE_USER_HOME to a stable path or using the Job Cacher plugin on clean agents.

On persistent agents, set GRADLE_USER_HOME to a shared path so the dependency cache survives. On ephemeral agents, use the Job Cacher cache step keyed on the build files.

Job Cacher for the Gradle home

The cache step restores and saves the Gradle home keyed on the build files between runs.

Jenkinsfile
pipeline {
  agent any
  environment {
    GRADLE_USER_HOME = "${WORKSPACE}/.gradle"
  }
  stages {
    stage('Build') {
      steps {
        cache(maxCacheSize: 1000, caches: [
          arbitraryFileCache(
            path: "${WORKSPACE}/.gradle/caches",
            cacheValidityDecidingFile: "build.gradle"
          )
        ]) {
          sh './gradlew build --build-cache'
        }
      }
    }
  }
}

Gotchas

  • Core Jenkins has no native cache - install the Job Cacher plugin or rely on a sticky-agent GRADLE_USER_HOME.
  • Pinning GRADLE_USER_HOME into the workspace ties the cache to a workspace; a clean checkout wipes it unless cached separately.
  • Add --build-cache so Gradle reuses task outputs in addition to downloaded dependencies.

Verify it actually works

Validate the pipeline definition against the running controller before committing. Jenkins parses declarative pipelines strictly, and a syntax error surfaces as a failed build rather than a clear parse message.

Terminal
# validate a Jenkinsfile against the live controller
curl -X POST -F "jenkinsfile=<Jenkinsfile" \
  https://your-jenkins/pipeline-model-converter/validate

# replay a build with modified script to test a change without committing
# Build page -> Replay -> edit -> Run

Agent and workspace assumptions that break in CI

  • An agent label that matches no online agent leaves the build queued indefinitely rather than failing.
  • Workspaces are reused between builds by default, so stale files from a previous run can mask or cause failures. Use cleanWs() or a fresh workspace when correctness matters.
  • Tools resolved from the controller PATH are not necessarily on the agent PATH. Declare them in a tools block or install them in the pipeline.
  • Credentials bound with withCredentials are masked in logs but still visible to any process you launch; avoid passing them as command-line arguments.

Frequently asked questions

How do I cache Gradle Dependencies in a Jenkins Pipeline?
On persistent agents, set GRADLE_USER_HOME to a shared path so the dependency cache survives. On ephemeral agents, use the Job Cacher cache step keyed on the build files.
Job Cacher for the Gradle home?
The cache step restores and saves the Gradle home keyed on the build files between runs.

Related guides

References

Run this faster and cheaper on Latchkey managed runners - self-healing included. Start free → 30-day trial · No credit card