如何使用Jenkinsfile设置github提交状态不使用拉取请求构建器

时间:2017-04-04 18:17:09

标签: github jenkins jenkins-pipeline jenkins-2

我们已经设置了Jenkins 2来构建对github的每次推送,并且我们不使用Pull Request构建器(尽管提交拉动请求的一部分显然也会被构建)。 GitHub Integration Plugin表示它只适用于拉取请求构建器,因此这对我们不起作用。

我也试过github-notify plugin,但似乎不适用于我们的情况(可能是因为回购是私有的和/或作为组织的一部分而不是个人用户)。我试过让它推断设置以及手动指定credentialsIdaccountrepo,当然还有status个参数,都没有运气。

这是我Jenkinsfile的缩写版本:

pipeline {
    agent { label "centos7" }

    stages {
        stage("github => pending") {
            steps {
                githubNotify status: "PENDING", credentialsId: "my-credentials-id", account: "my-account", repo: "my-repo"
            }
        }
        stage("build") {
            ...
        }
    }

    post {
        success {
            githubNotify status: "SUCCESS", credentialsId: "my-credentials-id", account: "my-account", repo: "my-repo"
        }
        failure {
            githubNotify status: "FAILURE", credentialsId: "my-credentials-id", account: "my-account", repo: "my-repo"
        }
    }
}

当我运行构建时,我得到以下内容:

java.lang.IllegalArgumentException: The suplied credentials are invalid to login
    at org.jenkinsci.plugins.pipeline.githubstatusnotification.GitHubStatusNotificationStep.getGitHubIfValid(GitHubStatusNotificationStep.java:234)
    at org.jenkinsci.plugins.pipeline.githubstatusnotification.GitHubStatusNotificationStep.getRepoIfValid(GitHubStatusNotificationStep.java:239)
    at org.jenkinsci.plugins.pipeline.githubstatusnotification.GitHubStatusNotificationStep.access$100(GitHubStatusNotificationStep.java:75)
    at org.jenkinsci.plugins.pipeline.githubstatusnotification.GitHubStatusNotificationStep$Execution.run(GitHubStatusNotificationStep.java:344)
    at org.jenkinsci.plugins.pipeline.githubstatusnotification.GitHubStatusNotificationStep$Execution.run(GitHubStatusNotificationStep.java:326)
    at org.jenkinsci.plugins.workflow.steps.AbstractSynchronousNonBlockingStepExecution$1$1.call(AbstractSynchronousNonBlockingStepExecution.java:47)
    at hudson.security.ACL.impersonate(ACL.java:221)
    at org.jenkinsci.plugins.workflow.steps.AbstractSynchronousNonBlockingStepExecution$1.run(AbstractSynchronousNonBlockingStepExecution.java:44)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

我已经通过Jenkins(在配置系统区域中)和在浏览器中手动测试了凭据 - 用户名和密码是正确的,并且对相关的回购具有读/写权限。

5 个答案:

答案 0 :(得分:10)

根据Jenkins GitHub plugin's own example

void setBuildStatus(String message, String state) {
  step([
      $class: "GitHubCommitStatusSetter",
      reposSource: [$class: "ManuallyEnteredRepositorySource", url: "https://github.com/my-org/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 {
  stages {
     ...
  }
  post {
    success {
        setBuildStatus("Build succeeded", "SUCCESS");
    }
    failure {
        setBuildStatus("Build failed", "FAILURE");
    }
  }
}

不需要多余的插件。只要您安装并正确配置了GitHub插件,您甚至不需要执行上述操作,它应该自动执行。我们没有使用Pull Request构建器,而是使用Jenkins Multibranch Pipeline。我们只是在我们的PR中使用上面的代码片段来获得额外的状态粒度。

答案 1 :(得分:5)

首先,确保这些凭据是全局的,而不是文件夹凭据 后者尚不支持,并会生成类似的错误消息:请参阅JENKINS-42955(仍在审核中)

其次,如果这些凭证在浏览器中有效但不通过DSL配置文件,则可能是jenkins文件,这可能是由于名称或密码中的特殊字符造成的:看看你是否不必{{3} }。

答案 2 :(得分:1)

我没有想到account参数中的值必须与凭据中的用户不匹配。在account中,您必须指定存储库所有者。在credentialsId中,您可以使用push access的任何用户访问存储库:

  

credentialsId:要使用的github凭据的ID必须是UsernameAndPassword类型。确保凭据具有写访问权限,如stated by doc:具有推送访问权限的用户可以为给定的参考创建提交状态

     

account:拥有存储库的帐户

答案 3 :(得分:0)

文档中的一个更好的例子:

def getRepoURL() {
  sh "git config --get remote.origin.url > .git/remote-url"
  return readFile(".git/remote-url").trim()
}

def getCommitSha() {
  sh "git rev-parse HEAD > .git/current-commit"
  return readFile(".git/current-commit").trim()
}

def updateGithubCommitStatus(build) {
  // workaround https://issues.jenkins-ci.org/browse/JENKINS-38674
  repoUrl = getRepoURL()
  commitSha = getCommitSha()

  step([
    $class: 'GitHubCommitStatusSetter',
    reposSource: [$class: "ManuallyEnteredRepositorySource", url: repoUrl],
    commitShaSource: [$class: "ManuallyEnteredShaSource", sha: commitSha],
    errorHandlers: [[$class: 'ShallowAnyErrorHandler']],
    statusResultSource: [
      $class: 'ConditionalStatusResultSource',
      results: [
        [$class: 'BetterThanOrEqualBuildResult', result: 'SUCCESS', state: 'SUCCESS', message: build.description],
        [$class: 'BetterThanOrEqualBuildResult', result: 'FAILURE', state: 'FAILURE', message: build.description],
        [$class: 'AnyBuildResult', state: 'FAILURE', message: 'Loophole']
      ]
    ]
  ])
}

答案 4 :(得分:0)

如果您不想打扰专用插件,可以使用curl

post {
  success {
    withCredentials([usernamePassword(credentialsId: 'your_credentials_id', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) {
      sh 'curl -X POST --user $USERNAME:$PASSWORD --data  "{\\"state\\": \\"success\\"}" --url $GITHUB_API_URL/statuses/$GIT_COMMIT'
    }
  }
  failure {
    withCredentials([usernamePassword(credentialsId: 'your_credentials_id', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) {
      sh 'curl -X POST --user $USERNAME:$PASSWORD --data  "{\\"state\\": \\"failure\\"}" --url $GITHUB_API_URL/statuses/$GIT_COMMIT'
    }
  }
}

GITHUB_API_URL的结构通常是这样的,例如在environment指令中:

environment {
   GITHUB_API_URL='https://api.github.com/repos/organization_name/repo_name'
}

可以从credentialsId创建和获取Jenkins -> Credentials