'How to reuse workspaces between branches with multibranch pipeline on Jenkins?

I've set up multibranch pipeline to track my repo and automatically build and test for all merge requests. It works wonders, however, I noticed that Jenkins creates a new workspace for each new branch. It is a pretty big project with a heavy build process and a lot of non-tracked cache files, that mostly stay valid from one version to another - so if instead of a fresh git checkout it would re-use previous workspace, it would build much faster (and also not use up so much hard drive space).

How can I configure it to re-use the same workspace for different branches?



Solution 1:[1]

After researching the issue, I found out that this is not something I can do with multibranch pipeline, so I switched to using the regular pipeline project. Now every build uses one of the available workspaces, so they end up re-using previous workspaces and the same cache files that really speed up the build.

Solution 2:[2]

Jenkins for MultiBranch projects by default uses isolated workspaces for every branch. Jobs within the same branch use the same workspace.

A possible solution for you is to use ws(path) inside a pipeline.

node("agent_name") {
    ws(workspacePath) {
        echo '...'      
        // ..
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Max Yankov
Solution 2 cheburek