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

后端 未结 10 1977
佛祖请我去吃肉
佛祖请我去吃肉 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:07

    One of the options is to use Jenkins REST API. I researched for another options, but seems that this is only one available with pipelines functionality.

    You should write script which polls Jenkins for info of current jobs running and check whether job of same type is running. To do this you should use Jenkins REST API, documentation you may find in the right bottom corner in your Jenkins page. Example script:

    #!/usr/bin/env bash
    
    # this script waits for integration test build finish
    # usage: ./wait-for-tests.sh  
    jenkins_user=$1
    jenkins_token=$2
    build_number=$3
    
    job_name="integration-tests"
    branch="develop"
    
    previous_build_number=build_number
    let previous_build_number-=1
    previous_job_status=$(curl -s http://${jenkins_user}:${jenkins_token}@jenkins.mycompany.com/job/mycompany/job/${job_name}/branch/${branch}/${previous_build_number}/api/json | jq -r '.result')
    
    while [ "$previous_job_status" == "null" ];
    do
        previous_job_status=$(curl -s http://${jenkins_user}:${jenkins_token}@jenkins.mycompany.com/job/mycompany/job/${job_name}/branch/${branch}/${previous_build_number}/api/json | jq -r '.result')
        echo "Waiting for tests completion"
        sleep 10
    done
    
    echo "Seems that tests are finished."
    

    I've used bash here, but you may use any language. Then just call this script inside of your Jenkinsfile:

    sh "./wait-for-tests.sh ${env.REMOTE_USER} ${env.REMOTE_TOKEN} ${env.BUILD_NUMBER}"
    

    So it will wait until job completion (don't be confused with integration-test mentions, it's just job name).

    Be also aware that in rare cases this script may cause deadlock when both jobs are waiting for each other, so you may want to implement some max retry policies here instead of infinite waiting.

提交回复
热议问题