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

ssgvzors  于 2023-02-11  发布在  Jenkins
关注(0)|答案(5)|浏览(195)

我们设置了Jenkins 2来构建每一个推送到GitHub的请求,并且我们没有使用Pull Request构建器(尽管作为Pull Request一部分的提交显然也会被构建)。GitHub集成插件说它只能与Pull Request构建器一起工作,所以这对我们来说不起作用。
我也尝试过github-notify plugin,但它似乎不适合我们的情况(可能是因为存储库是私有的和/或作为组织的一部分而不是个人用户拥有)。我尝试过让它推断设置以及手动指定credentialsIdaccountrepo,当然还有status参数,但都没有成功。
以下是我的Jenkins档案的缩略版:

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(在 Configure System 区域)和在浏览器中手动测试了凭据-用户名和密码正确,并且具有对相关存储库的读/写访问权限。

0md85ypi

0md85ypi1#

根据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 builder,而是使用Jenkins Multibranch Pipeline。我们只是在PR中使用上面的代码片段来增加状态粒度。

4ngedf3f

4ngedf3f2#

首先,确保这些凭据是全局凭据,而不是文件夹凭据。
后者尚不受支持,并将生成类似的错误消息:参见JENKINS-42955(仍在评审中)
第二,如果这些凭证在浏览器中工作,但不能通过DSL配置文件(位于jenkinsfile中)工作,则可能是由于用户名或密码中的特殊字符:看看你是否不需要对保留字符进行百分比编码。

wecizke3

wecizke33#

我没有想到account参数中的值不能与凭据中的用户匹配。在account中,您必须指定存储库所有者。在credentialsId中,您可以使用任何具有push access的用户访问存储库:
credentialsId:要使用的github凭据的ID必须是UsernameAndPassword类型。确保凭据具有写访问权限,如stated by doc:具有推送访问权限的用户可以为给定引用创建提交状态
account:拥有存储库的帐户

bnlyeluc

bnlyeluc4#

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

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']
      ]
    ]
  ])
}
hfsqlsce

hfsqlsce5#

如果您不想使用专门的插件,这里有一个使用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'
}

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

相关问题