How do I run a stage in Jenkins only on pull request?

蹲街弑〆低调 提交于 2021-01-24 08:50:15

问题


I have a Jenkinsfile-based pipeline with several stages in it right now that is triggered by webhook on every commit to Github. I'd like to keep the "build" and "unit tests" stages running on every commit, but ONLY run the "integration tests" stage when the branch is up for pull request.

What I want:

stage("build)"{
    // runs every commit
}
stage("unit tests"){
    // runs every commit
}
stage("integration tests"){
    // runs ONLY on pull request
}

I've been unable to find a solution to this, any ideas?


回答1:


After asking in the #jenkins IRC channel I was pointed in the right direction. This is possible using the https://wiki.jenkins.io/display/JENKINS/SCM+Filter+Branch+PR+Plugin

Scripted pipeline:

if(env.CHANGE_ID) {
// do something because it's a pull request
} else {
// not a pull request
}

Declarative pipeline:

pipeline {
stages {
    stage('Example Deploy') {
        when {
            allOf {
                environment name: 'CHANGE_ID', value: ''
                branch 'master'
            }
        }
        steps {
            // not a pull request so do something
        }
    }
}

}




回答2:


I found very easy way for declarative pipeline without any plugins and can be used anywhere.

        stage (' PR check ') {
        when {
                branch 'PR-*'  
            }

            steps {
            sh '''
            echo "PULL REQUEST CHECK IS DONE HERE"
            '''

            }

        }



回答3:


I would use the the built-in condition of Jenkins changeRequest().

stage ("sample") {
    when {
        anyOf {
            changeRequest()
            branch BRANCH_MAIN
        }
    steps {
            // not a pull request so do something
    }
   }

}

Doc: https://www.jenkins.io/doc/book/pipeline/syntax/#stages



来源:https://stackoverflow.com/questions/48102612/how-do-i-run-a-stage-in-jenkins-only-on-pull-request

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!