How to make Git commit to trigger a job/build in Jenkins CI

In this blog post I will show you how to configure a post commit hook on Git that notifies a Jenkins CI server about repository changes. This means that whenever a new commit is pushed to the Git repository, the cURL command line tool will be launched to initiate a Http request telling Jenkins to trigger a job.

1. Execute Jenkins build with Curl

In this setup, there is no authentication at Jenkins, considering that I will be responsible for the repository and jenkins server.

To test, I had to execute jenkins with curl


(Test)mmphego@dbelab04:~/src/mkat_fpga_tests/.git/hooks (GIT_DIR!)
|_ [2017-04-05 11:58:47] $ >>> curl -D - -X POST http://dbelab04:8080/job/mkat_fpga_tests_4k/build

HTTP/1.1 201 Created
Date: Wed, 05 Apr 2017 09:59:23 GMT
X-Content-Type-Options: nosniff
Location: http://dbelab04:8080/queue/item/387/
Content-Length: 0
Server: Jetty(9.2.z-SNAPSHOT)

2. Configure a hook of repository

Create a file in .git/hooks called post-commit and do not forget to make it executable.

$ nano $(pwd)/.git/hooks/post-commit

#!/bin/bash
# Jenkins-Git build trigger
# Mpho Mphego

machine=$(uname -n)
echo 'Notifying Jenkins Server to execute a Build on' $machine
curl -X POST http://$machine:8080/job/mkat_fpga_tests_4k/build

Screenshot_2017-04-05_12-57-44

Assumptions:
Git version > 2.6
Jenkins version > 2.0
Git Plugin (Jenkins)
Gitlab hook (Jenkins)

3. Configure Jenkins 

Configure your Jenkins job to be able to “Trigger builds remotely”

Screenshot_2017-04-05_13-18-19.png

Enable SCM polling for each project you want to notify:

  1. Go to the Dashboard.
  2. Click on your project.
  3. Click Configure.
  4. Under Build Triggers check the box for Poll SCM.
  5. Repeat for any other projects.

The notification you send tells Jenkins to poll the repository, so projects will only respond if SCM polling is enabled.

 

Now Jenkins will runs automatically when I/we commit and push using Git via CLI.

Done.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s