Add validation checks for GitHub pull requests - github

I'd like to add a validation check on every PR for the master branch to my GitHub repo (for integration with our Bamboo CI).
That is, each push to the master branch will trigger a Bamboo build, which must pass prior to that push being ready to merge.
On the repo's Settings page under "Branch protection for master"-->"Require status checks to pass before merging"
I don't see a status check option for the Bamboo build. How can I add it?
I've already added the Bamboo service in the Webhooks & Services section of the repo settings, and tested that the service can properly trigger a Bamboo build with the "Test service" button.

There is an old Bamboo plugin GitHub Status. You can try to install it.
If that doesn't help, there is always an option to add a couple of custom scripts which will post statuses via GitHub Status API.
In fact, it's very simple, all you need is just to make a POST request to your repo:
POST /repos/:owner/:repo/statuses/:sha
{
"state": "success",
"target_url": "https://example.com/build/status",
"description": "The build succeeded!",
"context": "continuous-integration/jenkins"
}
where :sha is a commit which triggered the build. It's stored in environment variable {bamboo.planRepository.revision}.

Related

Triggering Jenkins Multibranch Pipeline automatically if a PR is raised on GitHub

I am using Jenkins Multibranch pipeline.
I've configured the APIs (github-webhook and ghprbhook) on GitHub.
Currently, If I click on "Scan Repository Now/Scan Repository Log" in Jenkins, the Jenkins will go through the GitHub and creates a new PR job in Jenkins if there are any PR on GitHub.
So I need to trigger this Multibranch pipeline whenever there is a Pull Request raised on GitHub. I want this pipeline to trigger automatically when there is a PR on GitHub.
What do I need to do to achieve this approach?
Is it possible to trigger Multibranch pipeline automatically whenever a PR is raised on GitHub?
To achieve this, I have selected only "Push and Pull Request" under "Let me select individual events" section of GitHub Webhooks.
PS: The GitHub branches are automatically detected in Jenkins.
Du you use the GitHub pull request builder plugin?
This Jenkins plugin builds pull requests from GitHub and will report the results directly to the pull request via the GitHub Commit Status API
When a new pull request is opened in the project and the author of the pull request isn't whitelisted, builder will ask Can one of the admins verify this patch?. One of the admins can comment ok to test to accept this pull request for testing, test this please for one time test run and add to whitelist to add the author to the whitelist.
If an author of a pull request is whitelisted, adding a new pull request or new commit to an existing pull request will start a new build.
A new build can also be started with a comment: retest this please.

Showing Jenkins pipeline status against pull requests in GitHub

I have recently started using Jenkins Pipelines and have a multibranch job configured which is happily picking up Jenkinsfile on one of my branches.
I have seen in screenshots on posts\articles that Jenkins can report back to pull requests in GitHub the status of whether the branch has passed\failed checks performed in the pipeline.
I am not seeing any such feedback for my pull request I have opened, I can see in Jenkins it has triggered a pipeline build which has passed.
How can I get the notification to show the pipeline checks have passed in GitHub. Do I need to configure something else?
I found out this was simply down to me using the Git instead of GitHub sources option when configuring the multibranch pipeline job in Jenkins.
The docs for the GitHub Branch Source plugin gave me the clues!
I now get status messages on my pull requests showing whether pipeline checks are pending\failed\passed.
Check out the Github Pull Request Builder Plugin, it should do what you require: https://wiki.jenkins-ci.org/display/JENKINS/GitHub+pull+request+builder+plugin

How to trigger Jenkins Builds from Github Pull Requests

Using an organization type project in jenkins, I expected the pull requests to get automatically built.
I have a github webhook created in github settings. but nothing seems to be done?
Is there anything i need to put in my jenkinsfile to make this happen

How to trigger a Jenkins 2.0 Pipeline job from a GitHub pull request

It looks like the GitHubPullRequestBuilder is not compatible with Jenkins v2.0 pipeline jobs.
How do you configure a pipeline job to be triggered from a GitHub pull request event?
The documentation on this topic is sparse and I cannot find any examples of this. Or is it better to create a web-hook in GitHub to trigger the pipeline job on the PR event?
I had similar issue. Here’s what worked for me
Pre-req
Jenkins ver. 2+ (I was using Jenkins 2.60)
Github (or Githhub
enterprise) account
Your github and Jenkins must be able to talk to
each other.
On Github
create a github Personal Access Token (PAT) with relevant rights.
For your repo, create a webhook with
URL as YourJenkinsURL/github-webhook/
Choose ‘Let me select individual events’ and check ‘Pull Request’
Add a Jenkinsfile to the root folder of your repo. For testing purpose you could put content as a basic hello world like below
pipeline {
agent any
stages {
stage('Test') {
steps {
echo 'Hello World ...'
}
}
}
}
On Jenkins
Install GitHub Pull Request Builder plugin. (You also need “Github” plugin but that should normally be installed as part of Jenkins ver 2+)
Jenkins – Credentials
Add github Personal Access Token (PAT) as a ‘secret text’ credential.
Add github username-password as ‘username-password’ credential.
Manage Jenkins – Configure System
Github – Github Servers : This is part of the Github plugin. Add a github server. ‘API URL’ It will default to https://api.github.com. If you are using enterprise github, replace with enterprise github url followed by /api/v3. For credential select the PAT option. Test the connection. ‘Manage Hooks’ is checked.
GitHub Pull Request Builder : for ‘GitHub Server API URL’ use same url as specified in Github Server section. Leave ‘Shared Secret’ blank. For credentials use ‘username-password’ credential. Test credentials to ensure its working. In my settings, ‘Auto-manage webhooks’ was checked.
Pipeline Job
Create a new item using ‘Pipeline’ option. Note: This is the vanilla Pipeline job, not Multibranch Pipeline.
General Section: Check ‘Github Project’ – Project URL : Enter your github repo url
Build Triggers: Check ‘GitHub Pull Request Builder’
For ‘GitHub API credentials’ select option you set for GitHub pull request builder in ‘Manage Jenkins – Configure System’ screen
For admin list: add your username
Check Use github hooks for build triggering
Pipeline:
Select ‘Pipeline Script from SCM’. Note this assumes that the root folder of your repo will contain a ‘Jenkinsfile’
SCM: Select ‘Git’
Repositories – enter repo detail. For credentials use ‘username-password’ based credentials.
Click Advanced and add refspec as +refs/pull/*:refs/remotes/origin/pr/*
Branch – should be ${sha1}
Script Path: defaulted to Jenkinsfile, leave as is.
Lightweight Checkout - Uncheck this (https://github.com/jenkinsci/ghprb-plugin/issues/507)
That’s it. You are all set. Creating a PR on master branch of your repo should now trigger your Jenkins Pipeline job
Some observations
Redelivering the webhook payload of a PR from github does not trigger the pipeline but opening a new PR or even re-opening a closed PR on github, triggers the pipeline job
In Pipeline Job Configuration, if you choose “Pipeline Script” and paste your pipeline script in there, the job doesn't trigger !!!
The flow in a nutshell can go like this:
You create your pipeline as code and save it in a file called Jenkinsfile at the root dir of your project. That code should describe how your project will get built. See here for examples: https://jenkins.io/doc/pipeline/examples/
Then you should create a new "Multibranch Pipeline Project" item in your Jenkins. You should set this up so as to scan your repo of step 1.
Now whenever you get a new PR branch opened on your step 1 repo, the branch will be checked-out and will get built according to the Jenkinsfile instructions included with it. You can set up more conditions on what gets built and when if you want to.
Notes:
"Multibranch Pipeline Project" example documentation: https://jenkins.io/doc/book/pipeline-as-code/ (scroll down to Multibranch Pipeline Projects)
Keep in mind that getting the plugin to build a PR after commending on the PR does not work. There is a discussion analyzing this here: https://github.com/jenkinsci/gitlab-plugin/issues/298 There are workarounds (also described in that discussion) but they are quite messy to set up.
The most straightforward way to use Pipeline with GitHub pull requests is to put the script into your repository under the name Jenkinsfile and then install the GitHub Branch Source plugin. Documentation
Follow the Below Steps for Triggering Jenkins Job Automatically on Pull request generated on GitHub
Create a web hook on GitHub i.e. http:///generic-
webhook-trigger/invoke
Content Type :application/json
Select Pull Request as event Now github Configuration Part is done.
Jenkins Job Configuration
Download Generic Webhook Trigger in Jenkins
Git Hub Configuration On Jenkins
Git Hub Configuration
7.Select Generic Webhook Trigger on jenkins
8.Generic Webhook Trigger Configuration on Jenkinsand follow step 9
9.After doing step 7 Jenkins job will get trigger on PullRequest
10.Step 8 required to get information from Pull request Payload
11.Branch configuration inside Generic Webhook Trigger to get Branch details from Pull Request
Thanks

Show current state of Jenkins build on GitHub repo

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.
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.
Go to GitHub, log in, go to Settings, Developer Settings, Personal access tokens and click on Generate new token.
Check repo:status (I'm not sure this is necessary, but I did it, and it worked for me).
Generate the token, copy it.
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.
Go to your Jenkins server, log in.
Manage Jenkins → Configure System
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.
Verify that it works with the Test Credential button. Save the settings.
Find the Jenkins job and add Set build status on GitHub commit to the post-build steps
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.
You should see green checkmarks:
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:
Configure Github: Create Personal Access Token with OAuth Scope repo:status
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.
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.
Check your result on GitHub: Check if you get the build status and build execution duration on your GitHub commit.
Configure Github
Configure Jenkins
Configure Jenkins Job
Result
You will now see the status for your commits and branches:
What I did is quite simple:
Install the Hudson Post Task Plugin
Create a Personal Access Token here : https://github.com/settings/tokens
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!\"
}"
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!\"
}"
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!\"
}"
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:
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:
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.
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:
If you have the GitHub plugin installed on your Jenkins, you can do it in the Post build actions like this:
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/)
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:
Navigate to Settings > Branches.
Under Protect branches, click on
the Choose a branch drown down menu and select the branch you want
to set as a Protected branch.
Enable the options as needed.
On the Jenkins Server:
(Make sure you have the Git and GitHub Plugin installed)
Navigate to Manage Jenkins > Configure System.
Under GitHub, set the API URL to https://api.github.com. Though this is the default value.
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.
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/
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.
Jently updates your GitHub commit status (as described by vonc), but unfortunately they have yet to implement the Repo Status API.
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
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 settings → Developer settings → Personal 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:
Here is a section of a YouTube video in which he goes over the above steps.
Read about OAuth