Show current state of Jenkins build on GitHub repo

GithubJenkins

Github Problem Overview


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.

Github Solutions


Solution 1 - Github

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

Solution 2 - Github

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

Solution 3 - Github

What I did is quite simple:

  1. Install the Hudson Post Task Plugin

  2. Create a Personal Access Token here : https://github.com/settings/tokens

  3. Add a Post Task Plugin that always put 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 put 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

Solution 4 - Github

This plugin should work: https://wiki.jenkins-ci.org/display/JENKINS/Embeddable+Build+Status+Plugin

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

build passing

Solution 5 - Github

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.

Solution 6 - Github

There's also this plugin that will give you a badge url that you can post in your README.md and looks like this

build passing

https://wiki.jenkins-ci.org/display/JENKINS/Embeddable+Build+Status+Plugin

Solution 7 - Github

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

set build status on github

Solution 8 - Github

Add below line in your README.md and change both URL according to your jenkins project.

[![Build Status](https://jenkins../..project/lastBuild/buildStatus)](https://jenkins../..project/lastBuild/)

Solution 9 - Github

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.

Solution 10 - Github

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/

Solution 11 - Github

Edit:

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

Update: what I ended up doing, for our specific case: (above 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 in 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 .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 config, we have:

  • Compile checks
  • unit & integration tests
  • Test Reports
  • Code Coverage Reports
  • API Docs
  • 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 Docs, test results and test coverage.

Solution 12 - Github

Jently updates your Github commit status (as described by @vonc above), unfortunately they have yet to implement the Repo Status API

Solution 13 - Github

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 repo.

> Reference : https://stackoverflow.com/a/47162309/4261333

Solution 14 - Github

Adding to this answer, and also to this one They have answered the question but 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 we can create the token going to the GH settings -> Developer settings -> Personal access tokens then for public GH repo just check repo:status, and for private repo check the whole repo section
  • After creating your access token you need to add it to ur Jenkins server:
  • Copy and paste the access token to the GitHub plugin section settings, under ur Jenkins configurations
  • Create a GH 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 U create ur pipeline.

Resources:

  • Here is a section of a YT video in which he goes over the above steps.
  • Read about OAuth

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJasper BluesView Question on Stackoverflow
Solution 1 - GithubMarius GedminasView Answer on Stackoverflow
Solution 2 - GithubAlexView Answer on Stackoverflow
Solution 3 - GithubNatimView Answer on Stackoverflow
Solution 4 - GithubKoraktorView Answer on Stackoverflow
Solution 5 - GithubVonCView Answer on Stackoverflow
Solution 6 - Githubmholm815View Answer on Stackoverflow
Solution 7 - GithubRémyView Answer on Stackoverflow
Solution 8 - GithubKaushalView Answer on Stackoverflow
Solution 9 - Githubd' ghostmanView Answer on Stackoverflow
Solution 10 - GithubAdan AmarillasView Answer on Stackoverflow
Solution 11 - GithubJasper BluesView Answer on Stackoverflow
Solution 12 - GithubchernjieView Answer on Stackoverflow
Solution 13 - GithubMawardyView Answer on Stackoverflow
Solution 14 - GithubamshrboView Answer on Stackoverflow