Skip to content

Instantly share code, notes, and snippets.

@dkinzer
Last active July 29, 2019 20:29
Show Gist options
  • Save dkinzer/15709b1f119c57261e824238f6c6029f to your computer and use it in GitHub Desktop.
Save dkinzer/15709b1f119c57261e824238f6c6029f to your computer and use it in GitHub Desktop.

How to trigger a Jenkins job when merging to master on GitHub

Sometimes you want be able to trigger a jenkins job whevever you merge to master.
Fortunately there is a very useful Jenkins Plugin called Generic Webhook Trigger Plugin to help. This plugin is not specific to GitHub. It should work with any service that can post to a webhook.

The plugin let's you parse the JSON payload using either JSONPath or XPath; it even let's you set up key values based on the POST Headers or URL arguments. The variables you set can be available as extra environment variables in a shell job, but they can also be used to trigger the job itself by setting a filter configuration.

Configure a job to trigger on a push to master.

  • Install generic-webhook-trigger-plugin
  • Go to or create a new job that you want to trigger on a push event.
  • (Optional) in the Build Triggers section click the "Trigger builds remotely" checkbox
    • Add an authentication token
  • Click the "Generic Webhook Trigger" checkbox:
    • Add a post content parameter; Value: repo_name, Expression: $.repository.name
    • Add a post content parameter; Value: reference, Expression: $.ref
    • Add a headers parameter; Request header: X-Github-Event
    • Add an optional filer; Expression: push foo refs\/heads\/master, Text: $X_GitHub_Event $repo_name $reference
  • Save your work.

Now as long as you have configured your GithHub webhook properly (see below), the next push to master on the foo repo will trigger this job.

Set up GitHub Webhook:

  • Go to the webhook page: https://github.com///settings/hooks
  • Click on "Add Webhook"
  • Configure the Payload URL: https://jenkinshost/generic-webhook-trigger/invoke?token=TOKEN
    • The token is optional, add it if you are configuring your job to require it.
  • Make sure you set Content Type to application/json
  • Leave secret blank (not sure what that's for)
  • For which events to trigger, use the default Just the push event or anything else that includes a push event.

Troubleshooting

  • Make sure that the anonyous user has read access to jobs
  • Test that your job works if you post vs relying on GitHub:
curl -H "Content-Type: application/json" \
     -X POST \
     -d '{ "repository": { "name": "foo" } }' \
     http://localhost/jenkins/generic-webhook-trigger/invoke
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment