|
| 1 | +# Lock Specific Stages |
| 2 | + |
| 3 | +For long-running builds where a resource is only needed for part of the pipeline, |
| 4 | +you can lock individual stages instead of the entire build. This allows other |
| 5 | +jobs to use the resource while your build performs tasks that don't require it. |
| 6 | + |
| 7 | +## Lock a single stage |
| 8 | + |
| 9 | +Use the `options` block to lock a resource for just one stage: |
| 10 | + |
| 11 | +```groovy |
| 12 | +pipeline { |
| 13 | + agent any |
| 14 | + stages { |
| 15 | + stage('Build') { |
| 16 | + steps { |
| 17 | + echo 'Building for 27 minutes...' |
| 18 | + echo 'Resource foo is not locked' |
| 19 | + } |
| 20 | + } |
| 21 | + stage('Deploy') { |
| 22 | + options { |
| 23 | + lock(label: 'foo', quantity: 1) |
| 24 | + } |
| 25 | + steps { |
| 26 | + echo 'Deploying for 3 minutes...' |
| 27 | + echo 'Resource foo is locked' |
| 28 | + } |
| 29 | + } |
| 30 | + stage('Verify') { |
| 31 | + steps { |
| 32 | + echo 'Verifying...' |
| 33 | + echo 'Resource foo is not locked anymore' |
| 34 | + } |
| 35 | + } |
| 36 | + } |
| 37 | +} |
| 38 | +``` |
| 39 | + |
| 40 | +## Lock multiple consecutive stages |
| 41 | + |
| 42 | +To lock a resource across multiple stages, nest them inside a parent stage |
| 43 | +with the lock option: |
| 44 | + |
| 45 | +```groovy |
| 46 | +pipeline { |
| 47 | + agent any |
| 48 | + stages { |
| 49 | + stage('Build') { |
| 50 | + steps { |
| 51 | + echo 'Building...' |
| 52 | + echo 'Resource foo is not locked' |
| 53 | + } |
| 54 | + } |
| 55 | + stage('Deploy and Test') { |
| 56 | + options { |
| 57 | + lock(label: 'foo', quantity: 1) |
| 58 | + } |
| 59 | + stages { |
| 60 | + stage('Deploy') { |
| 61 | + steps { |
| 62 | + echo 'Deploying...' |
| 63 | + echo 'Resource foo is locked' |
| 64 | + } |
| 65 | + } |
| 66 | + stage('Integration Test') { |
| 67 | + steps { |
| 68 | + echo 'Testing...' |
| 69 | + echo 'Resource foo is still locked' |
| 70 | + } |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | + stage('Cleanup') { |
| 75 | + steps { |
| 76 | + echo 'Cleaning up...' |
| 77 | + echo 'Resource foo is not locked anymore' |
| 78 | + } |
| 79 | + } |
| 80 | + } |
| 81 | +} |
| 82 | +``` |
| 83 | + |
| 84 | +## When to use this pattern |
| 85 | + |
| 86 | +This pattern is useful when: |
| 87 | + |
| 88 | +- Your build has a long preparation phase that doesn't need the locked resource |
| 89 | +- You want to maximize resource utilization across multiple jobs |
| 90 | +- Only specific stages (like deployment or testing) require exclusive access |
| 91 | + |
| 92 | +## See also |
| 93 | + |
| 94 | +- [Locking multiple stages in declarative pipeline](locking-multiple-stages-in-declarative-pipeline.md) |
0 commit comments