The following post is an example of how to set up a git post-receive hook to trigger a Jenkins build. As soon as someone checks in new code and pushes it to the develop branch then we need to ensure a fast feedback loop.

Hook templates

For every git project there will be a folder called ‘.git’. Inside of it there will be a hooks folder with default sample scripts which are well-commented.

You might notice that there is no post-receive sample and the git documentation it mentions there is a sample script called post-receive-email in the git repository. For a summarized version of this, visit this github page for post-receive sample.

In a nutshell, the 3 main parameters needed for the script are ” {oldrev} {newrev} {refname}” via standard input (stdin) where rev refers to the revision. In order to read from it, we need to use a while construct – how to get the refname.

Set up the post-receive hook

Create a file called “post-receive” in .git/hooks/ on the git server repo where you will push code to.

Now to make good use of the incoming parameters, we need to do something with them. In this case we want to make sure that the branch where the code was pushed to is in fact ‘develop’ before triggering the build. Git has a command called rev-parse that will allow us to transform this data.

View reference documentation for rev-parse:

$ git rev-parse --help
$ git help rev-parse

Add in the logic and replace placeholders:


project_name='{Project Name}'
echo ============================================================
echo Post receive event for $project_name

while read oldrev newrev refname
    branch=$(git rev-parse --symbolic --abbrev-ref $refname)

	if [ $branch_to_build == "$branch" ]; then
	    echo Changes detected on branch: $branch  
		echo Triggering $project_name pipeline on Jenkins.

        # Post is inferred
		curl --user {user}:{token} -s $url \
        --data-urlencode json='{"parameter": [{"name":"BRANCH", "value":"'$branch_to_build'"}]}'	
echo ============================================================

Jenkins uses a concept of parameterized builds. These can be triggered using a remote access API which is what the above HTTP Post curl request will do.

More information:

Git Hooks – Atlassian

What does git rev-parse do?

Leave a comment

Your email address will not be published. Required fields are marked *