Making Jenkins and Github ACTUALLY integrate with each other
Tags: jenkins, github, integration, pullrequest
Published: 2019-08-22 14:31:20

---
title: Making Jenkins and Github ACTUALLY integrate with each other
published: true
description: Integrating jenkins and github
tags: jenkins, github, integration, pull-request
---



		
	
		

		
<div class="wp-block-media-text alignwide"><figure class="wp-block-media-text__media"><img src="//jenkins.io/images/logos/fire/256.png" alt="An alternative of the jenkins logo where the mascot is on fire" class="wp-image-841"/></figure><div class="wp-block-media-text__content">
<p class="has-large-font-size"></p>



<p>You may need to build jenkins jobs when branches/PRs are made from within the repository &#8211; say, to run tests. You may also want to report on the test status when finished. And you may have found doing this quite frustrating. If these things are true, join me on a journey&#8230;</p>
</div></div>



<h2>Introduction</h2>



<p>For a work project, I needed to integrate Jenkins tests with Github repositories. Basically, we make pull requests from branches within the repository against master, and then merge them when review and testing passes. For running automated tests, we use Jenkins, and so we want to be able to trigger the jenkins job when a PR is created and also change the PR check status to passed or failed depending on the results.</p>



<h2>Assumptions</h2>



<p>There are many different ways of doing these things, so it&#8217;s quite important that I list my assumptions early on so that you don&#8217;t waste your time reading a blog post that doesn&#8217;t actually help you. These assumptions held true for the case that I wanted to solve, and your circumstances may well be different.</p>



<ul><li>You don&#8217;t use Jenkins multibranch pipelines &#8211; if you do, certain things will be easier, but there still may be information here that helps you.</li><li>You want to build PRs from branches within the same repository (as is the case for most private/corporate projects) rather than PRs from forks (as is the case for most FOSS projects).</li></ul>



<h2>Requirements</h2>



<ul><li>2GB of RAM or more, Jenkins is very memory hungry&#8230;</li><li>A Jenkins installation &#8211; if you&#8217;re like me and don&#8217;t want to experiment on your company&#8217;s actual Jenkins install, it may be smart to invest in a  Linux box such as a DigitalOcean, AWS, Linode, or other cloud provider virtual machine.

<br>Since it needs to be able to receive Github webhooks, it has to be accessible from the Internet, or from wherever you&#8217;re hosting your Github Enterprise instance. Thus, you unfortunately most likely can&#8217;t get away with just playing with this on a local VM or docker container &#8211; sorry! But some of the cloud providers mentioned above have hourly pricing, so it shouldn&#8217;t cost you too much.</li><li>A Github project that you want to integrate with, duh!</li><li>A way to relax (trust me, you&#8217;ll need it&#8230;)</li><li>A lot of patience</li></ul>



<h2>Setup</h2>



<h3>Github Access</h3>



<p>The first step is setting up Github settings in a way that allow Jenkins to update PR status. Technically, it doesn&#8217;t matter if you do this step or the next step first, but it&#8217;s part of laying down the groundwork for later. Unfortunately, as much as we try to group things that need to be done in Github and Jenkins separately, we&#8217;ll need to go between the two platforms quite a lot, so get ready for that.</p>



<p>Having said that, I&#8217;ll try to put as many things that are done on a single platform together as physically possible, so if something doesn&#8217;t make sense right away, don&#8217;t worry, it&#8217;ll all come together eventually. I hope.</p>



<h4>Make a user with write access</h4>



<p>First, make sure you have a user with <strong>write access</strong> to your repository that you can use for this. Don&#8217;t worry, we won&#8217;t end up allowing Jenkins to have full write access, but due to how Github works this is required. You can use an already existing user or make a new one and you can lock it down as much as you feel you need to to make sure it&#8217;s safe.</p>



<h4>Create a personal access token</h4>



<p>Personal access tokens allow access to the Github API by using a token instead of your username and password. In addition to this, they can be locked down to only have the permissions that are absolutely necessary. As such, this is one of the safest ways to integrate with any service.</p>



<ul><li>Go to Github Settings (Accessible by clicking on your avatar on the top right)</li><li>Click on <strong>developer settings</strong> near the bottom.</li><li>Click on <strong>personal access tokens</strong>.</li><li>Click <strong>generate new token</strong></li><li>For this, the only required scope is &#8220;<strong>repo:status</strong>&#8220;. This means that the token that you are generating can be used to <strong>update commit status</strong>, but can&#8217;t be used for anything else.</li><li><strong>Save the token somewhere, you won&#8217;t be able to get it again</strong>. We&#8217;ll need it again later on in the post to set up Jenkins integration.</li></ul>



<h3>Jenkins plugins &amp; setup</h3>



<p>Now that that&#8217;s done, we need to do the groundwork to allow Github to trigger Jenkins builds, so let&#8217;s head over to our jenkins install for this next step.</p>



<p>For this task, you just need the <strong>Github plugin</strong> for Jenkins. This provides a webhook URL, which is <code>&lt;YOUR_JENKINS_INSTANCE_URL/github-webhook></code>. You can visit that URL manually to see if it works; if you see &#8220;Method POST required&#8221; then it&#8217;s already set up.</p>



<h2>Integration</h2>



<p>Now that you have Github access set up and the Jenkins plugin installed, it&#8217;s go time!</p>



<h3>Create Jenkins job</h3>



<p>If you already have the job you want to use, you can edit it so that it matches these settings instead.</p>



<ul><li>Go to your Jenkins install</li><li>Click &#8216;<strong>create item</strong>&#8216;</li><li>Click &#8216;<strong>freestyle project&#8217;</strong> &#8211; once again we&#8217;re assuming you&#8217;re not using pipelines. If you are, then your life is much easier.</li><li>Tick <strong>github project</strong> and add your project URL</li><li>Add the repository in <strong>source code management</strong> &#8211; this requires either the credentials of a user with at least read-only access, or for your repository to be public.</li><li>Leave <strong>branches to build</strong> blank so you can build PR branches.</li><li>Select at least the <strong>&#8216;GitHub hook trigger for GITScm polling&#8217;</strong></li><li>Add a <strong>build step</strong> that runs your tests; I&#8217;ll leave this one to you.</li><li>Click &#8216;save&#8217; for now; we will need to make more edits later, but it&#8217;s good to get the base case working first.</li></ul>



<h3>Trigger Jenkins builds from Github</h3>



<p>Remember the github-webhook URL from earlier? It&#8217;s that url&#8217;s time to shine. Time to add it as a webhook in our github repo, so that it triggers builds.</p>



<ul><li>Go to <strong>settings</strong> within your github repo</li><li>Click on <strong>Webhooks</strong></li><li>Put the <strong>payload URL</strong> as the URL from earlier, e.g. <code>YOUR_JENKINS_INSTANCE_URL/&lt;github-webhook></code>.</li><li>Select &#8220;send me <strong>everything</strong>&#8220;. I&#8217;m not sure it&#8217;s required but it really doesn&#8217;t matter.</li><li>Save the webhook.</li></ul>



<p>Now, make a PR with at least one commit. If all goes well, you should see the job build in jenkins:</p>



<figure class="wp-block-image"><img src="//www.errietta.me/blog/wp-content/uploads/2019/08/image.png" alt="" class="wp-image-847"/></figure>



<p>If it doesn&#8217;t go well, click &#8216;<strong>Github Hook Log</strong>&#8216; and hope that you can diagnose the problem. If not, you may need your <strong>patience </strong>and <strong>ways of relaxing</strong> from the <strong>Requirements</strong> section, plus a heavy dose of <strong>StackOverflow.</strong></p>



<p><strong>At this stage, github won&#8217;t report the job status. This is normal! We&#8217;ll fix this in the next step!</strong></p>



<h3>Reporting the job status</h3>



<p>I&#8217;d advise taking a break at this point, because this is by far the most frustrating step.</p>



<p>Welcome back! Hopefully you&#8217;ve had a long meditation session/drink/whatever keeps you sane when doing really annoying things.</p>



<p>Now it&#8217;s time to get to the final and most frustrating part of the process &#8211; actually updating GH build status. Are you ready?</p>



<h4>Creating a jenkins secret to store the token</h4>



<p>Did you save the token earlier? No? Don&#8217;t worry, you can just make another. Now that you have a token, time to store it securely* in Jenkins.</p>



<p><code>*</code> They&#8217;re encrypted but can be decrypted if someone has access to the jenkins instance. Hopefully, you&#8217;ve secured it, right?</p>



<ul><li>Click <strong>credentials</strong> from the home page</li><li>Click on the credential store where you want to store it. If you have no idea what that means (I sure don&#8217;t), click on the &#8216;Jenkins&#8217; store.</li><li>Click on the domain, such as &#8220;global credentials&#8221;</li><li>Click on &#8220;add credentials&#8221;</li><li>Kind is &#8220;secret text&#8221;</li><li>The secret is your token from earlier.</li><li>Select a meaningful id and description</li></ul>



<h4>Add the secret to your job</h4>



<ul><li>Go back to your jenkins job and click on &#8216;configure&#8217;, which is conveniently placed right next to the &#8216;delete job&#8217; button, which you don&#8217;t want to accidentally click.</li><li>Within &#8220;Build environment&#8221;, check <strong>Use secret text(s) or file(s)</strong></li><li>In bindings, select &#8216;secret text&#8217;. This should expand a new dialog.</li><li>In variable, type in the name of the environment variable you want to use, such as GH_TOKEN</li><li>Select &#8220;Specific Credentials&#8221; and select the id of the secret you made in the previous step</li></ul>



<h4>Report status to github</h4>



<p>Now, it&#8217;s time for the true task! Report the status back to Github. While still on the same configure page, it&#8217;s time to tweak the build job slightly.</p>



<p>Put the following <strong>before</strong> running your test command, to set the status as pending:</p>



<pre class="wp-block-code"><code>export REPO_NAME='YOUR_REPO_NAME'
export JOB_NAME='YOUR_JOB_NAME'


curl "//api.GitHub.com/repos/$REPO_NAME/statuses/$GIT_COMMIT
      ?access_token=$GH_TOKEN" \
-H "Content-Type: application/json" \
-X POST \
-d "{
    \"state\": \"pending\",
    \"context\": \"jenkins/$REPO_NAME\",
    \"description\": \"Jenkins\",
    \"target_url\": \"//YOUR_JENKINS_URL/job/$JOB_NAME/$BUILD_NUMBER/console\"
}"</code></pre>



<p>This will set your git commit to pending!</p>



<p>Now, because we&#8217;re not using pipelines, and because you don&#8217;t want the job to stop if it fails, you need to change your test command. So if your command is, say, <code>bash test.sh</code>, you need to change it thusly, so that you capture if it succeeds or not. <strong>This makes the assumption that your command will return a non-zero status if it fails, </strong>which is true for most test frameworks.</p>



<p>First <code>export TEST_ERROR=0</code>, we&#8217;ll use this to store the error if any</p>



<p>Change your command from <code>bash test.sh</code> to <code>bash test.sh || TEST_ERROR=$?</code></p>



<p>Now, when you want to report the status, you can check if we caught an error or not:</p>



<pre class="wp-block-code"><code>if [ $TEST_ERROR -eq 0 ] ; then
    curl "//api.GitHub.com/repos/$REPO_NAME/statuses/$GIT_COMMIT
          ?access_token=$GH_TOKEN" \
    -H "Content-Type: application/json" \
    -X POST \
    -d "{
        \"state\": \"success\",
        \"context\": \"jenkins/$REPO_NAME\",
        \"description\": \"Jenkins\",
        \"target_url\": \"//YOUR_JENKINS_URL/job/$JOB_NAME/$BUILD_NUMBER/console\"
    }"
else
    curl "//api.GitHub.com/repos/$REPO_NAME/statuses/$GIT_COMMIT?access_token=$GH_TOKEN" \
    -H "Content-Type: application/json" \
    -X POST \
        -d "{
        \"state\": \"failure\",
        \"context\": \"jenkins/$REPO_NAME\",
        \"description\": \"Jenkins\",
        \"target_url\": \"//YOUR_JENKINS_URL/job/$JOB_NAME/$BUILD_NUMBER/console\"
    }"


    exit $TEST_ERROR
fi
</code></pre>



<p>This will run a hook to update to success or failure, depending on the value of <code>$TEST_ERROR</code>. It&#8217;ll also exit with a non-zero status if there was a failure before, telling jenkins to record the failure as well.</p>



<h2>That&#8217;s it!</h2>



<p>If you&#8217;ve done everything right, you should see the status reported to GH, either success or failure:</p>



<figure class="wp-block-image"><img src="//www.errietta.me/blog/wp-content/uploads/2019/08/image-1.png" alt="" class="wp-image-849"/></figure>



<figure class="wp-block-image"><img src="//www.errietta.me/blog/wp-content/uploads/2019/08/image-3.png" alt="" class="wp-image-851"/></figure>



<p>Congratulations! After much pain, you have a working integration. </p>



<h2>Further steps</h2>



<ul><li>You <strong>probably</strong> want to look into jenkins multibranch pipelines so you can at the very least programmatically act on build status without having to write a hacky shell script.</li></ul>



<h2>Thanks</h2>



<p>Thanks to the blog posts <a href="//dzone.com/articles/adding-a-github-webhook-in-your-jenkins-pipeline">&#8220;adding a github webhook in your jenkins pipeline&#8221;</a> and<a href="//applitools.com/blog/how-to-update-jenkins-build-status-in-github-pull-requests-step-by-step-tutorial?utm_referrer=//www.google.com/"> &#8220;how to update jenkins build status in github&#8221;</a>, which were extremely helpful to me. Even though I couldn&#8217;t directly replicate what they did, my solution is really a Frankenstein&#8217;s monster-style stitch up of both of them, so yay for them.</p>



<p>Thanks for the wonderful folks at the <a href="//jenkins.io/artwork/">jenkins artwork page</a> for the image used as a featured image for this post. As much as I complain about jenkins, it&#8217;s probably one of the most powerful CI tools I&#8217;ve ever used.</p>



<p>And thank you for reading! Let me know if you want me to make myself suffer further by making a write-up about multi branch pipelines! I&#8217;m sure watching me attempt to write Groovy will be amusing to someone&#8230;</p>



<p>And apologies if this post seems more passive-aggressive than my usual style, but to my defense this was a real adventure&#8230;</p>