prkz.de - Blog


Keep it simple

Jenkins: Using lockable resource across multiple stages

written on 20 May 2021
The Jenkins [Lockable Resources](https://plugins.jenkins.io/lockable-resources/) plugin is nice, but its documentation (as with many Jenkins components) is fairly scarce and often not self-explanatory. The slightly more detailed reference for the lock resource is documented [here](https://www.jenkins.io/doc/pipeline/steps/lockable-resources/). Of course, you can use it in a scripted pipeline or as a step in a declarative pipeline: ```java pipeline { stages { stage('my-stage') { steps { lock('my-resource') { ... } } } } } ``` However, what I wanted, and what is is to let my Jenkins job (a declarative pipeline) acquire a Lock *once* when the whole Job started and release it when all stages are completed (success or fail). Luckily, there's a [this StackOverflow thread](https://stackoverflow.com/questions/44098993/how-to-lock-multiple-stages-of-declarative-jenkins-pipeline), that shows that you can actually use the `lock()` in the `options` section of a Jenkins pipeline: ```java pipeline { options { lock('my-resource') } stages { stage('stage-1') { ... } stage('stage-2') { ... } } } ``` What is nowhere documented is its exact behaviour: **The lock gets acquired *once* for the entire job and is *not* released between stages**. Alternatively, you can use a "parent" stage and acquire the lock for it once: ```java pipeline { stages { stage('my-parent-stage') { options { lock('my-resource') } stages { stage('stage-1') { ... } stage('stage-2') { ... } } } } } ``` In this case, the behavior is immediately obvious, but you need 2 additional indent levels...