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

$ ~/src/mkat_fpga_tests/.git/hooks (GIT_DIR!)
$ >>> 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 .git/hooks/post-commit

    
    #!/bin/bash
    # Jenkins-Git build trigger
    # Username
    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.