gitjenkinspull-request

Trigger Jenkins build when pull request is merged in Github


This should be an easy, out-of-the-box configuration in Jenkins but I haven't found anything straightforward on the internet. All I want to do is a trigger a build ONLY when a pull request i merged in our Github repo.

To start with, Github aggregates almost all activity around the pull request into one webhook (versus bitbucket which allows you to differentiate between actions).

enter image description here

On the Jenkins side I've seen posts point towards the Generic Webhook Plugin which allows you to ingest the json of the webhook and create variables, however from here it looks like those need to be used in a script in order to trigger/not trigger a build.

Github Pull Request Build is another popular plugin, but again there is nothing explicit that states "only trigger this build when a PR is merged" or even seems to give the option of looking for a specific value in the webhook json.

Unless there are other plugins out there I haven't found the best option (i.e. least configuration to just get the build started) is to configure the GitHub hook trigger for GITSCM polling in Jenkins and on the Github side send the webhook only on push events... however this isn't the exact behavior we're looking for.

enter image description here

Right now this is all being done via the UI, and it's been awhile since I've used Jenkins so maybe the declarative pipeline infrastructure has passed the UI by, but it seems like this should be much more intuitive. Can someone explain the easiest implementation they've found, using Jenkins and Github, to trigger a build ONLY when a pull request is merged to a specific branch?


Solution

  • No need for webhooks anymore, since you now have GitHub Actions (assuming you are using github.com, although the Actions are coming with GHE, GitHub Enterprise, in Beta, starting Sept. 2020).

    As explained on this thread, you can trigger, on GitHub side, a job when a pull request is merged on master:

    on:
      pull_request:
        branches:
          - master
        types: [closed]
    
    jobs:
      <job id>:
        if: github.event.pull_request.merged == true
        steps: // the rest of the code
    

    And that job can then use a GitHub Action like Trigger Jenkins Job for GitHub Actions, which will call your Jenkins and trigger one or several Jenkins jobs.

    jobs:
    
      build:
        name: Build
        runs-on: ubuntu-latest
        steps:
        - name: trigger single Job
          uses: appleboy/jenkins-action@master
          with:
            url: "http://example.com"
            user: "example"
            token: ${{ secrets.TOKEN }}
            job: "foobar"
    

    After discussion with the OP and following the GitHub Actions tutorial, I confirm that: