How to run gradle build in Jenkins with a clean environment?

Using the following Jenkins Groovy script and Gradle 6.7.1, observing “Could not create parent directory for lock file /home/ubuntu/.gradle/…/” error in Jenkins run.

stage('Run build'){
     steps {
                sh "./gradlew --update-locks assembleDebug"
                sh "./gradlew -DinputParam=${PARAM} --info clean test"

This build was working in the past, but now causing this lock file issue., Also tried adding --refresh-dependencies still same run time issue observed.

                sh "./gradlew build --refresh-dependencies"

Please advice what is the best approach to have a clean gradle build and to fix this runtime issue.


As far as I am concerned, I had to apply a rule of thumb: one project = one workspace = one gradle user home. There are files that do not support concurrent access in the gradle user home and that cannot be shared accross several runners.

This is inefficient regarding disk use, but it should work:

stage('prepare') {
    env.GRADLE_USER_HOME = "$WORKSPACE/.gradle"
stage('Run build') {
    // ...

@Pierre1 , thanks for the prepare step, it did work.

By one project = one workspace rule, are you suggesting using a docker container and running tests within be a better way. Please suggest.


Sorry for the delay.
By “one workspace” I meant that I keep things simple and do not try to cheat the build system. For each project that has a Jenkinsfile, it builds in its own workspace, and run Gradle with a GRADLE_USER_HOME local to that workspace. That way I have no concurrency issue, but each build has it own cache for dependencies and there is no way to mutualize that.

Regarding docker, or any other container technology, it is a good way to have isolation provided that:

  1. the additional costs of pulling / storing images is acceptable
  2. build user home dir is not mounted between host and container