Search code examples
jenkinsjenkins-pipelinegitlab-cipipelinepull-request

How can we set, to trigger a Jenkins job when a Pull request is created from Gitlab using Jenkinsfile


I don't want to use the webhook option in Gitlab. also the Jenkins job should be automatically triggered when the pull request is created.

i Tried as per this - https://about.gitlab.com/handbook/customer-success/demo-systems/tutorials/integrations/create-jenkins-pipeline/

This only showing gitlab pipeline error but no jenkins job is triggering.


Solution

  • Is there a specific reason why you don't want to use a GitLab webhook? Webhooks are the common way to start builds from SCM. GitLab also has official documentation on how you can achieve your goal using webhooks:

    https://docs.gitlab.com/ee/integration/jenkins.html

    The tutorial covers all the steps end to end from creating access tokens to allow Jenkins to access your repo, to setting up the webhook which will be responsible for triggering the builds.

    If you do not want to use webhooks, you can use a longer method to trigger your builds when a PR is created. You will need to first create a polling Job in Jenkins that runs every couple of minutes and calls the GitLab Merge requests API (doc). Get all the open PRs, which will be potential candidates for a build. Since you don't want to build a PR that has already been built, you will need to get the latest commit in a PR (doc).

    Then, check if that commit has been already built. If not, trigger a downstream job that builds the commit. Once the build finishes, make sure to update the build status for the commit saying that it has been built so that it doesn't get built again.

    As you can see, it is a roundabout method, but it is your best option without using webhooks.