6

We have a project on GitHub which has two Jenkins Multibranch Pipeline jobs - one builds the project and the other runs tests. The only difference between these two pipelines is that they have different JenkinsFiles.

I have two problems that I suspect are related to one another:

  1. In the GitHub status check section I only see one check with the following title: continuous-integration/jenkins/pr-merge — This commit looks good, which directs me to the test Jenkins pipeline. This means that our build pipeline is not being picked up by GitHub even though it is visible on Jenkins. I suspect this is because both the checks have the same name (i.e. continuous-integration/jenkins/pr-merge).
  2. I have not been able to figure out how to rename the status check message for each Jenkins job (i.e. test and build). I've been through this similar question, but its solution wasn't applicable to us as Build Triggers aren't available in Multibranch Pipelines

If anyone knows how to change this message on a per-job basis for Jenkins Multibranch Pipelines that'd be super helpful. Thanks!

Edit (just some more info):

We've setup GitHub/Jenkins webhooks on the repository and builds do get started for both our build and test jobs, it's just that the status check/message doesn't get displayed on GitHub for both (only for test it seems). Here is our JenkinsFile for for the build job:

#!/usr/bin/env groovy 
properties([[$class: 'BuildConfigProjectProperty', name: '', namespace: '', resourceVersion: '', uid: ''], buildDiscarder(logRotator(artifactDaysToKeepStr: '', artifactNumToKeepStr: '', daysToKeepStr: '', numToKeepStr: '5')), [$class: 'ScannerJobProperty', doNotScan: false]])
node {
    stage('Initialize') {
        echo 'Initializing...'
        def node = tool name: 'node-lts', type: 'jenkins.plugins.nodejs.tools.NodeJSInstallation'
        env.PATH = "${node}/bin:${env.PATH}"
    }

    stage('Checkout') {
        echo 'Getting out source code...'
        checkout scm
    }

    stage('Install Dependencies') {
        echo 'Retrieving tooling versions...'
        sh 'node --version'
        sh 'npm --version'
        sh 'yarn --version'
        echo 'Installing node dependencies...'
        sh 'yarn install'
    }

    stage('Build') {
        echo 'Running build...'
        sh 'npm run build'
    }

    stage('Build Image and Deploy') {
        echo 'Building and deploying image across pods...'
        echo "This is the build number: ${env.BUILD_NUMBER}"
        // sh './build-openshift.sh'
    }

    stage('Upload to s3') {
        if(env.BRANCH_NAME == "master"){
            withAWS(region:'eu-west-1',credentials:'****') {
                def identity=awsIdentity();
                s3Upload(bucket:"****", workingDir:'build', includePathPattern:'**/*');
                cfInvalidate(distribution:'EBAX8TMG6XHCK', paths:['/*']);
            }
        };
        if(env.BRANCH_NAME == "PRODUCTION"){
            withAWS(region:'eu-west-1',credentials:'****') {
                def identity=awsIdentity();
                s3Upload(bucket:"****", workingDir:'build', includePathPattern:'**/*');
                cfInvalidate(distribution:'E6JRLLPORMHNH', paths:['/*']);
            }
        };
    }
}
JP Strydom
  • 248
  • 3
  • 10
  • Did you check [this](https://stackoverflow.com/a/47162309/10721592) answer? – biruk1230 Jan 28 '19 at 10:29
  • I had a look at it but it didn't seem to fit into our JenkinsFile structure. We're running a node project so I don't know if the files will be different. I'll add a copy of our JenkinsFile to the question so you can have a look at it - I have very little experience with JenkinsFiles, so any help will be appreciated. – JP Strydom Jan 29 '19 at 08:07
  • Replied in answer. – biruk1230 Jan 29 '19 at 09:42

4 Answers4

4

You can use the Github Custom Notification Context SCM Behaviour plugin https://plugins.jenkins.io/github-scm-trait-notification-context/

After installing go to the job configuration. Under "Branch sources" -> "GitHub" -> "Behaviors" click "Add" and select "Custom Github Notification Context" from the dropdown menu. Then you can type your custom context name into the "Label" field.

csanchez
  • 1,623
  • 11
  • 20
3

Try to use GitHubCommitStatusSetter (see this answer for declarative pipeline syntax). You're using a scripted pipeline syntax, so in your case it will be something like this (note: this is just prototype, and it definitely must be changed to match your project specific):

#!/usr/bin/env groovy 
properties([[$class: 'BuildConfigProjectProperty', name: '', namespace: '', resourceVersion: '', uid: ''], buildDiscarder(logRotator(artifactDaysToKeepStr: '', artifactNumToKeepStr: '', daysToKeepStr: '', numToKeepStr: '5')), [$class: 'ScannerJobProperty', doNotScan: false]])
node {

    // ...

    stage('Upload to s3') {
        try {
            setBuildStatus(context, "In progress...", "PENDING");

            if(env.BRANCH_NAME == "master"){
                withAWS(region:'eu-west-1',credentials:'****') {
                    def identity=awsIdentity();
                    s3Upload(bucket:"****", workingDir:'build', includePathPattern:'**/*');
                    cfInvalidate(distribution:'EBAX8TMG6XHCK', paths:['/*']);
                }
            };

            // ...

        } catch (Exception e) {
            setBuildStatus(context, "Failure", "FAILURE");
        }
        setBuildStatus(context, "Success", "SUCCESS");
    }
}

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

Please check this and this links for more details.

biruk1230
  • 3,042
  • 4
  • 16
  • 29
  • I'll try this out and report back. Thanks for all the help so far! – JP Strydom Jan 29 '19 at 09:57
  • I just tried this and it works! I can even set up checks for each stage in my pipeline which is super useful! Thanks for all the help @biruk1230. Resolved – JP Strydom Jan 29 '19 at 11:03
  • Glad it helped :) – biruk1230 Jan 29 '19 at 11:04
  • Sadly this solution stopped working for me today. I keep getting a "ERROR: [GitHub Commit Status Setter] - Cannot retrieve Git metadata for the build, setting build result to UNSTABLE" error message every time I run the `setBuildStatus` method. I've tried [this](https://issues.jenkins-ci.org/browse/JENKINS-54249?page=com.atlassian.jira.plugin.system.issuetabpanels%3Aall-tabpanel) solution but it did not work for me. Any ideas? – JP Strydom Feb 04 '19 at 12:00
  • If you already downgraded **GitHub** plugin, try to downgrade also **GitHub Branch Source** plugin, because seems to be that it's the issue with plugin updates. – biruk1230 Feb 04 '19 at 13:05
1

This answer is pretty much like @biruk1230's answer. But if you don't want to downgrade your github plugin to work around the bug, then you could call the API directly.

void setBuildStatus(String message, String state) 
{
    env.COMMIT_JOB_NAME = "continuous-integration/jenkins/pr-merge/sanity-test"
    withCredentials([string(credentialsId: 'github-token', variable: 'TOKEN')]) 
    {
        // 'set -x' for debugging. Don't worry the access token won't be actually logged
        // Also, the sh command actually executed is not properly logged, it will be further escaped when written to the log
        sh """
            set -x
            curl \"https://api.github.com/repos/thanhlelgg/brain-and-brawn/statuses/$GIT_COMMIT?access_token=$TOKEN\" \
                -H \"Content-Type: application/json\" \
                -X POST \
                -d \"{\\\"description\\\": \\\"$message\\\", \\\"state\\\": \\\"$state\\\", \
                \\\"context\\\": \\\"${env.COMMIT_JOB_NAME}\\\", \\\"target_url\\\": \\\"$BUILD_URL\\\"}\"
        """
    } 
}

The problem with both methods is that continuous-integration/jenkins/pr-merge will be displayed no matter what.

chb
  • 1,727
  • 7
  • 25
  • 47
real_kappa_guy
  • 313
  • 1
  • 4
  • 12
0

This will be helpful with @biruk1230's answer.
You can remove Jenkins' status check which named continuous-integration/jenkins/something and add custom status check with GitHubCommitStatusSetter. It could be similar effects with renaming context of status check.

Install Disable GitHub Multibranch Status plugin on Jenkins.
This can be applied by setting behavior option of Multibranch Pipeline Job on Jenkins.

Thanks for your question and other answers!

int-kim
  • 1
  • 1