Jenkinsfile check if build triggered by push or merge request

Viewed 5302

Right now I have configured jenkins gitlab connection and gitlab webhook to trigger jenkins jobs.

I would like to create Jenkinsfile where some tasks are executed only if build was triggered by push and some others only if build was triggered by merge request. I use pipeline jobs. Is that possible?

BUILD_CAUSE variable shows nothing.

Thanks.

4 Answers

Have a look at Jenkins Builtin Functions. You are probably looking for changeRequest:

Executes the stage if the current build is for a "change request" (a.k.a. Pull Request > on GitHub and Bitbucket, Merge Request on GitLab or Change in Gerrit etc.). When no parameters are passed the stage runs on every change request, for example: when { changeRequest() }.

  • If you are in a when block, you can use changeRequest variable as described here

  • If you are in a script block or in any other part of the pipeline, you can create a variable like this in the first stage and use it everywhere


def isPullRequest = false

pipeline {
  agent {
    // ....
  }
  stages {
    stage('First stage') {
      steps {
        script {
          isPullRequest = env.CHANGE_ID != null
        }
      }
    }
    // other stages...
  }
}
Related