How do I prevent two pipeline jenkins jobs of the same type to run in parallel on the same node?

后端 未结 10 2003
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-01 02:18

I do not want to allow two jobs of the same type (same repository) to run in parallel on the same node.

How can I do this using groovy inside Jenkinsfile ?

10条回答
  •  广开言路
    2020-12-01 03:10

    The "Throttle Concurrent Builds Plugin" now supports pipeline since throttle-concurrents-2.0. So now you can do something like this:

    Fire the pipeline below twice, one immediately after the other and you will see. You can do this manually by double-clicking "Build Now" or by invoking it from a parallel step in another job.

    stage('pre'){
        echo "I can run in parallel"
        sleep(time: 10, unit:'SECONDS')
    }
    throttle(['my-throttle-category']) {
        
        // Because only the node block is really throttled.
        echo "I can also run in parallel" 
        
        node('some-node-label') {
            
            echo "I can only run alone"
            
            stage('work') {
                
                echo "I also can only run alone"
                sleep(time: 10, unit:'SECONDS')
                
            }
        }
    }
    stage('post') {
        echo "I can run in parallel again"
        // Let's wait enough for the next execution to catch
        // up, just to illustrate.
        sleep(time: 20, unit:'SECONDS')
    }
    

    From the pipeline stage view you'll be able to appreciate this:

    However, please be advised that this only works for node blocks within the throttle block. I do have other pipelines where I first allocate a node, then do some work which doesn't need throttling and then some which does.

    node('some-node-label') {
    
        //do some concurrent work
    
        //This WILL NOT work.
        throttle(['my-throttle-category']) {
            //do some non-concurrent work
        }
    }
    

    In this case the throttle step doesn't solve the problem because the throttle step is the one inside the node step and not the other way around. In this case the lock step is better suited for the task

提交回复
热议问题