How to clear workspace in Jenkins pipeline before job starts

☆樱花仙子☆ 提交于 2019-12-09 16:22:12

问题


I need to clear workspace before build starts. I tried using cleanDir() in stages, but in the declarative pipeline, check out happens first and when stage with cleadDir runs, checked out code also gets cleared which is not desired. How can we clear the workspace before check out in the declarative pipeline?


回答1:


Use the means of your VCS, with Git run

git clean -fdx



回答2:


Actually, I have to revise my answer based on recent changes to the pipeline plugins, e.g. GitHub Branch Source Plugin 2.2.0 with JENKINS-43507.

Besides the different branch discovery behaviours, which can be configured, one can now define additional steps to take, including Clean before checkout (and Clean after checkout):

The resulting output in the pipeline execution will then be

Cleaning workspace
  > git rev-parse --verify HEAD # timeout=10
Resetting working tree
 > git reset --hard # timeout=10
 > git clean -fdx # timeout=10

so, pretty close to the calling git clean yourself.




回答3:


stage('Git') {
            steps {
                step([$class: 'WsCleanup'])
                checkout scm
            }
        }

the WsCleanup does the trick




回答4:


A slightly different approach would be to use the stash step to stash your code first:

stash includes: 'src/**', name: 'source-code'

After that you can delete everything in your current Workspace. In a later stage you can simply unstash the source code again:

unstash 'source-code'

Another advantage of stash/unstash is that you can use it to share files between multiple jenkins nodes.




回答5:


Something like this should work:

            env.WORKSPACE = pwd()
            sh "rm ${env.WORKSPACE}/* -fr"


来源:https://stackoverflow.com/questions/46118811/how-to-clear-workspace-in-jenkins-pipeline-before-job-starts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!