209

Is there a way to show the Jenkins build status on my project's GitHub Readme.md?

I use Jenkins to run continuous integration builds. After each commit it ensures that everything compiles, as well as executes unit and integration tests, before finally producing documentation and release bundles.

There's still a risk of inadvertently committing something that breaks the build. It would be good for users visiting the GitHub project page to know the current master is in that state.

Etienne Neveu
  • 12,604
  • 9
  • 36
  • 59
Jasper Blues
  • 28,258
  • 22
  • 102
  • 185
  • 1
    The Travis build server can do something like this, but I'm using Jenkins on Osx. Here's the kind of thing I'm after: https://github.com/CocoaPods/CocoaPods – Jasper Blues Jan 11 '13 at 08:50
  • possible duplicate of [How do show my tests passing/failing in Github?](http://stackoverflow.com/questions/13546097/how-do-show-my-tests-passing-failing-in-github) – random Jan 11 '13 at 22:24
  • 3
    The link to the similar question recommends Travis, which doesn't currently support iOS and OSX, so it does not answer the question. – Jasper Blues Feb 21 '13 at 02:52
  • 7
    This is not a duplicate.. travis != jenkins – Banjocat Jan 23 '16 at 21:20

14 Answers14

178

Ok, here's how you can set up Jenkins to set GitHub build statuses. This assumes you've already got Jenkins with the GitHub plugin configured to do builds on every push.

  1. Go to GitHub, log in, go to Settings, Developer Settings, Personal access tokens and click on Generate new token.

    screenshot of generate new token

  2. Check repo:status (I'm not sure this is necessary, but I did it, and it worked for me).

    screenshot of generate new token

  3. Generate the token, copy it.

  4. Make sure the GitHub user you're going to use is a repository collaborator (for private repos) or is a member of a team with push and pull access (for organization repos) to the repositories you want to build.

  5. Go to your Jenkins server, log in.

  6. Manage JenkinsConfigure System

  7. Under GitHub Web Hook select Let Jenkins auto-manage hook URLs, then specify your GitHub username and the OAuth token you got in step 3.

    screenshot of Jenkins global settings

  8. Verify that it works with the Test Credential button. Save the settings.

  9. Find the Jenkins job and add Set build status on GitHub commit to the post-build steps

    screenshot of Jenkins job configuration

That's it. Now do a test build and go to GitHub repository to see if it worked. Click on Branches in the main repository page to see build statuses.

sceenshot of the main page where you click on 'branches'

You should see green checkmarks:

screenshot of GitHub branches with build status

Dan Alvizu
  • 1,291
  • 9
  • 23
Marius Gedminas
  • 11,010
  • 4
  • 41
  • 39
  • GitHub have updated their authorisation workflow now, users no longer specify what to allow, rather applications must request what they require during authorization and the user approve the requested permissions. – Ian Vaughan Aug 14 '15 at 10:07
  • 8
    This does not seem to work with Jenkins > 1.609 and Github plugin v 1.13.3 - I cannot find the option "Let Jenkins auto-manage hook URLs" – endre Nov 12 '15 at 12:21
  • For the record, I'm currently on Jenkins 1.638 and GitHub plugin 1.11.3, and the GitHub Web Hook configuration in /configure matches the screenshot here. I also have GitHub Pull Request Builder plugin 1.22.4 and GitHub API Plugin 1.68. – Marius Gedminas Nov 18 '15 at 13:06
  • 2
    I concur with @pyeleven. I'm using Jenkins LTS 1.625.3 with Github Plugin 1.16.0 and Github API Plugin 1.71. This options does not show up. Rather I see a drop down for credentials, but no credentials are listed (even though I have credentials set up). These credentials appear when going to Advance-> Manage Additional Github Actions -> Convert Login and Password to Github token. – shehzan Jan 19 '16 at 16:22
  • The green checkmark seems to only show up for the branch (as you show), not for individual commits (as I'd hope), using Jenkins 2.0 and GitHub plugin 1.18.2. Is there a way to fix this? – Blaisorblade Apr 29 '16 at 18:02
  • 5
    This appears to be out of date; the post-build action this answer mentions is now marked as deprecated and there's a second one – Daenyth Aug 26 '16 at 14:32
  • Somehow the interface changed. I cannot enter a token directly. – Karsten Sep 02 '16 at 21:08
  • @MariusGedminas hi, do you know how to do this using jenkins version 2.7.2 ? I cannot seem to find the `Github webhook section` that you refer to, thanks – Richlewis Sep 26 '16 at 11:17
  • I'm afraid I don't know what the config UI looks like in modern Jenkins versions. I've a GitHub section in my Configure Jenkins page, but it is strangely empty. – Marius Gedminas Sep 27 '16 at 05:21
  • Oh, wait my work Jenkins server has something in there. I guess that part's not necessary if you manage push hooks on the GitHub side manually! – Marius Gedminas Sep 27 '16 at 05:23
  • This was very helpful to me as well: https://wiki.jenkins-ci.org/display/JENKINS/GitHub+Plugin#GitHubPlugin-AutomaticMode%28Jenkinsmanageshooksforjobsbyitself%29 – Gerard van Helden Oct 18 '16 at 08:33
  • Unfortunately, the github plugin references this answer , but I agree with others that it is simpler now and the instructions are not what I did to get it working. https://plugins.jenkins.io/github – AnneTheAgile Mar 13 '18 at 17:26
  • 3
    Now post build step parameters has been changed. @Alex has correct answer. – Bibek Mantree Nov 28 '18 at 14:09
  • 2
    If you use the latest Jenkins Blue Ocean plugin with GitHub to create a multi-branch pipeline, it does this automatically for you, provided you set up the token correctly with the necessary permissions described in this answer. – Abhijay Kumar Jul 20 '20 at 07:16
  • This answer is helpful for setting up Jenkins build status for pull requests, but it does not address OP's question about putting the build status in the project's README.md. – Cameron Hudson Dec 28 '20 at 22:11
84

In the meanwhile the UI of Jenkins and GitHub has changed a bit and it took me a while to figure out how to configure Jenkins now correctly. The explanation here is based on Jenkins version 2.121.1.

I also assume that you have already configured your Jenkins Job be triggered by a webhook or by polling. Those are the steps that I have taken to get it working:

  1. Configure GitHub: Create Personal Access Token with OAuth Scope repo:status
  2. Configure Jenkins: Configure System and add the OAuth Secret as a GitHub Server - use Secret Text as an authentication method to put the OAuth Secret in there.
  3. Configure your Jenkins Job: Add Set GitHub commit status as Post-build action. Set the Status Result to One of the default messages and statuses.
  4. Check your result on GitHub: Check if you get the build status and build execution duration on your GitHub commit.

Configure GitHub

Create Personal Access Token


Enter image description here


Enter image description here


Enter image description here


Configure Jenkins

Enter image description here


Enter image description here


Enter image description here


Enter image description here


Enter image description here


Configure Jenkins Job

Enter image description here


Enter image description here


Enter image description here


Result

You will now see the status for your commits and branches:

Enter image description here

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Alex
  • 1,652
  • 11
  • 18
  • 3
    Wow finally found a solution, thanks so much! That "Secret text" got me confused. – head01 Jul 10 '18 at 13:28
  • 1
    Jenkins seems to be pushing statuses, but my private repo is not picking up on them. Any suggestions? – Patrick Michaelsen Nov 26 '18 at 02:14
  • 2
    Update: my issue was related to the privacy of my repo. I must have an issue with my credential setup. – Patrick Michaelsen Nov 26 '18 at 02:37
  • 4
    Update: ultimately I discovered this only works if it was triggered by an actual git push. Running the build yourself doesn't trigger the status update correctly. – Patrick Michaelsen Nov 26 '18 at 04:33
  • 2
    The `Manage Hooks` box is highlighted but not ticked in the images above, does that mean it should be unticked when we save? – Perplexabot Jun 12 '19 at 00:49
  • Much helpful with screenshots corresponding to current Jenkins versions (in 2019.06) – BhaveshDiwan Jun 27 '19 at 15:55
  • This answer is helpful for setting up Jenkins build status for pull requests, but it does not address OP's question about putting the build status in the project's README.md. – Cameron Hudson Dec 28 '20 at 22:13
  • awesome screenshots but it doesn't work for me – Alexey Sh. Jan 14 '21 at 10:10
  • 2
    Extremely helpful screenshots and all, but this didn't work for me. The problem was the scope of the personal access token that I had generated - it needs the `Full control of private repositories` access, and NOT ONLY the `repo:status`. Hope this helps someone! – Roger Oba Feb 09 '21 at 07:11
  • 1
    These instructions cannot be followed for a pipeline job, since "Post-build actions" are not a thing for them. I'm currently still researching how to implement what `Set GitHub commit status (universal)` would do for a pipeline. I assume it would be a Groovy snippet to put into the relevant Jenkinsfile. – Steven Lu Jan 10 '22 at 21:03
  • @StevenLu is this Stackoverflow post what you are looking for? https://stackoverflow.com/questions/43214730/how-to-set-github-commit-status-with-jenkinsfile-not-using-a-pull-request-builde – Alex Jan 17 '22 at 19:26
  • @Alex Yes. that is the method I used to get it working, and it works great. Thanks for leaving the relevant link. – Steven Lu Jan 18 '22 at 00:58
  • Is it possible to add the credentials for this without being a Jenkins admin? Per project maybe. – Edson Passos Feb 25 '22 at 14:00
35

What I did was quite simple:

  1. Install the Hudson Post Task Plugin

  2. Create a Personal Access Token here: Personal access tokens (classic)

  3. Add a Post Task Plugin that always adds success

    curl -XPOST -H "Authorization: token OAUTH TOKEN" https://api.github.com/repos/:organization/:repos/statuses/$(git rev-parse HEAD) -d "{
      \"state\": \"success\",
      \"target_url\": \"${BUILD_URL}\",
      \"description\": \"The build has succeeded!\"
    }"
    
  4. Add a Post Task Plugin that will add failure if "marked build as failure"

    curl -XPOST -H "Authorization: token OAUTH TOKEN" https://api.github.com/repos/:organization/:repos/statuses/$(git rev-parse HEAD) -d "{
      \"state\": \"failure\",
      \"target_url\": \"${BUILD_URL}\",
      \"description\": \"The build has failed!\"
    }"
    
  5. You can also add a call to pending at the beginning of tests

    curl -XPOST -H "Authorization: token OAUTH TOKEN" https://api.github.com/repos/:organization/:repos/statuses/$(git rev-parse HEAD) -d "{
      \"state\": \"pending\",
      \"target_url\": \"${BUILD_URL}\",
      \"description\": \"The build is pending!\"
    }"
    

Screenshot of the Post build task configuration

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Natim
  • 17,274
  • 23
  • 92
  • 150
  • You can also do that from the Pipeline - for instance, you can just call it through `sh` and even leverage the Jenkins credentials storage with `withCredentials` – Ivan Kolmychek Jul 18 '16 at 16:06
  • For Teamcity you can use: https://confluence.jetbrains.com/display/TCD10/Commit+Status+Publisher – Natim Mar 20 '18 at 14:05
  • This answer does not address OP's question about putting the build status in the project's README.md. – Cameron Hudson Dec 28 '20 at 22:14
32

This plugin should work: Embeddable Build Status

You should be able to embed badges like this into your README.md file:

Build passing

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Koraktor
  • 41,357
  • 10
  • 69
  • 99
  • 6
    Sadly, it seems that GitHub started caching these images on some image hosting service, and they are being displayed incorrectly now. – axel22 Feb 12 '14 at 08:59
  • Now it works fine if you've correctly set up access (anonymous user should be able to see build status) – Dmitry Meshkov Jan 05 '16 at 10:31
11

The Commit Status API allows you to see the "Repo Statuses API".

And since April 26th 2013, you now can see the build status on your GitHub repo branch page:

build status on GitHub repo branches

That means it is another way, by visiting the GitHub project page, to see those statuses instead of having only Jenkins.

Starting April 30th, 2013, the API endpoint for commit statuses has been extended to allow branch and tag names, as well as commit SHAs.

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • Where do I put the URLs to hit? Is there a Plugin or do I have to user curls in a build step? – Ian Vaughan Nov 01 '13 at 15:20
  • @IanVaughan what do you mean "to hit"? To see what? To see a status, it would be a `curl` (http://developer.github.com/v3/repos/statuses/#list-statuses-for-a-specific-ref) – VonC Nov 01 '13 at 21:29
  • Sorry, yep, I knew that curl could be used, and I knew the API interface, it was more of where to put the curl, and if not a higher level abstraction from curl was available? i.e. I could add a curl POST in before the build starts to state the commit/PR is building, and then one after, but this all seems very low level, and was hoping there was a higher level plugin todo this stuff for me. – Ian Vaughan Nov 02 '13 at 22:11
  • I have since found Janky, which is quite heavy for my use-case, seems to do what I want. – Ian Vaughan Nov 02 '13 at 22:12
11

There's also the plugin Embeddable Build Status that will give you a badge URL that you can post in your README.md file, and it looks like this:

Build passing

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mholm815
  • 2,009
  • 19
  • 14
  • This is a repeat of [the first / highest-scored answer](https://stackoverflow.com/questions/14274293/show-current-state-of-jenkins-build-on-github-repo/14274631#14274631). – Peter Mortensen Mar 15 '23 at 17:44
6

If you have the GitHub plugin installed on your Jenkins, you can do it in the Post build actions like this:

Set build status on GitHub

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Rémy Virin
  • 3,379
  • 23
  • 42
  • 14
    [This appears to fail silently.](https://issues.jenkins-ci.org/browse/JENKINS-19775) – chrylis -cautiouslyoptimistic- Jul 26 '14 at 10:05
  • 5
    This answer lacks details: how do I create an OAuth access token on GitHub to let the GitHub plugin use the APIs necessary to set build status? What permissions are needed on this token? Where in Jenkins configuration can I specify the username/token? – Marius Gedminas Nov 13 '14 at 11:00
  • 3
    This is really not helpful, how do you get to this dialog window ? – oz123 Jul 04 '17 at 10:08
6

Add the below line in your README.md file and change both URLs according to your Jenkins project.

[![Build Status](https://jenkins../..project/lastBuild/buildStatus)](https://jenkins../..project/lastBuild/)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kaushal
  • 3,237
  • 3
  • 29
  • 48
3

In regards with setting up Jenkins and GitHub's protected branch. I'm using Jenkins 2.6, and these are the steps I did to make it work:

On your repository's GitHub webpage:

  1. Navigate to Settings > Branches.
  2. Under Protect branches, click on the Choose a branch drown down menu and select the branch you want to set as a Protected branch.
  3. Enable the options as needed.

On the Jenkins Server: (Make sure you have the Git and GitHub Plugin installed)

  1. Navigate to Manage Jenkins > Configure System.
  2. Under GitHub, set the API URL to https://api.github.com. Though this is the default value.
  3. Select your generated token for the Credentials. If you haven't generated a token yet, click on Advanced... then on Additional actions, you can convert your login and password to token and use it as your credential.

Also, make sure the GitHub account that your Jenkins is using is a collaborator for the repository. I've set it with write permission level.

Hope this helps.

2

I followed the directions from Alex and it worked.

But, for GitHub Enterprise you need to modify the API URL when adding the server to Jenkins.

For example, if your company is creditcard.com, your URL would be

https://github.creditcard.com/api/v3/

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Adan Amarillas
  • 219
  • 3
  • 4
2

For pipeline projects, you can use the post section like so:

void setBuildStatus(String message, String state) {
  step([
      $class: "GitHubCommitStatusSetter",
      reposSource: [$class: "ManuallyEnteredRepositorySource", url: "https://github.com/my-user/my-repo"],
      contextSource: [$class: "ManuallyEnteredCommitContextSource", context: "ci/jenkins/build-status"],
      errorHandlers: [[$class: "ChangingBuildStatusErrorHandler", result: "UNSTABLE"]],
      statusResultSource: [ $class: "ConditionalStatusResultSource", results: [[$class: "AnyBuildResult", message: message, state: state]] ]
  ]);
}

pipeline {
    agent any

    triggers {
        githubPush()
    }

    stages {

        stage('Hello') {
            steps {
                echo 'Hello World'
            }
        }

    }

    post {
        success {
            setBuildStatus("Build succeeded", "SUCCESS");
        }
        failure {
            setBuildStatus("Build failed", "FAILURE");
        }
    }
}

Just change "https://github.com/my-user/my-repo" to meet your GitHub repository.

Reference: How to set GitHub commit status with Jenkinsfile NOT using a pull request builder

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mawardy
  • 3,618
  • 2
  • 33
  • 37
1

I'm no longer using this approach. Please use one of the other answers.

What I ended up doing, for our specific case: (the previous answers were great - thanks!)

Because our build server is not on the Internet, we have a script to publish the build status to the gh-pages branch on GitHub.

  • Start of build stamps failing
  • End of build stamps success
  • Project runs after main project to publish results -> build-status, API docs, test reports and test coverage.

GitHub caches images, so we created a .htaccess file, that instructs a short cache timeout for the build-status image.

Put this in the directory with the build-status image:

ExpiresByType image/png "access plus 2 minutes"

Here's the build script. The target that publishes to gh-pages is '--publish.site.dry.run'

With less than 400 lines of configuration, we have:

  • Compile checks
  • Unit & integration tests
  • Test Reports
  • Code Coverage Reports
  • API documentation
  • Publishing to GitHub

. . and this script can be run in or outside of Jenkins, so that:

  • Developers can run this script before commit, reducing the chance of a broken build that impacts others.
  • A failure is easy to reproduce locally.

The Results:

Project main page has the build status, updated after each build, along with latest API documentation, test results and test coverage.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jasper Blues
  • 28,258
  • 22
  • 102
  • 185
1

Jently updates your GitHub commit status (as described by vonc), but unfortunately they have yet to implement the Repo Status API.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
chernjie
  • 453
  • 4
  • 6
0

I am adding to this answer, and also to this one. They have answered the question, but they didn't give us a proper intuition about the problem

So, here are my intuitions:

  • We need to add status to our GitHub commit. This status is based upon the results of our Jenkins build.

  • To do this, we need to give Jenkins access to the GitHub API, not to the repo. We do this through OAuth, and we can create the token going to the GitHub settingsDeveloper settingsPersonal access tokens. Then for a public GitHub repository just check repo:status, and for a private repository, check the whole repository section

  • After creating your access token you need to add it to your Jenkins server:

  • Copy and paste the access token to the GitHub plugin section settings, under your Jenkins configurations

  • Create a GitHub server. It defaults to api.github.com. And add the access token as a secret text credentials.

  • The last step is to add a post build settings when you create your pipeline.

Resources:

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131