首页 > 解决方案 > 在 Jenkins 管道中使用用户名和密码凭据对 Github 存储库进行身份验证

问题描述

我在 Jenkins 2.107.2 上创建了一个多分支管道。我想在克隆的存储库上执行诸如 等git commitGit命令。git push

为了对 GitHub 存储库进行身份验证,我使用 ( https://wiki.jenkins-ci.org/display/JENKINS/Credentials+Binding+Plugin ) 在 Jenkins 中配置了我的用户凭据。我尝试了几种方法来使用这些凭据进行身份验证,但它们会导致不同的错误。

第一种方法

stage('clone'){
        steps{
            checkout([$class: 'GitSCM', branches: [[name: '*/develop']],
 userRemoteConfigs: [[url: 'https://github.com:xyz/demo.git']]])
        }
    }
stage('prepare release'){
        steps{
            sh "sed -i 's/-SNAPSHOT//g' pom.xml"
            withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'jenkins-user-for-demo-github', usernameVariable: 'GITHUB_DEMO_CREDENTIALS_USR', passwordVariable: 'GITHUB_DEMO_CREDENTIALS_PSW']]) {
                sh "git add pom.xml"
                sh "git commit -m 'release version set"
            }
        }
    }

错误

*** 请告诉我你是谁。运行 git config --global user.email "you@example.com" git config --global user.name "Your Name"

第二种方法

stage('Checkout') {
        steps{
            git branch: 'develop', credentialsId: 'jenkins-user-for-demo-github', url: 'git@github.com:xyz/demo.git'
        }
    }
stage('prepare release'){
        steps{
            sh "sed -i 's/-SNAPSHOT//g' pom.xml"
            sh "git add pom.xml"
            sh "git commit -m 'release version set"
        }
    }

错误

引起:hudson.plugins.git.GitException:命令“git fetch --tags --progress git@github.com:AbhayChandel/New-project.git +refs/heads/ :refs/remotes/origin/ ”返回状态码128:stdout:stderr:主机密钥验证失败。致命:无法从远程存储库中读取。请确保您具有正确的访问权限并且存储库存在。

与这些错误作斗争我有以下问题:

  1. 是否可以从 Jenkinsfile 向 Github 存储库传递用户名和密码凭据以进行身份​​验证?
  2. 我应该使用 SSH 密钥而不是用户名和密码吗?
  3. 还有其他我应该尝试的方法吗(但不要太老套)?

标签: gitauthenticationgithubjenkins-pipeline

解决方案


“凭据”仅用于与 Git 服务器对话(例如,、、git clonegit fetchgit push不是用于操作本地存储库。因此,在您的第一个示例中,git 不会抱怨凭据而是抱怨在执行git commit. 您可以在这里设置任意内容,如下所示:

stage('clone'){
    steps{
      checkout([$class: 'GitSCM', branches: [[name: '*/develop']], userRemoteConfigs: [[url: 'https://github.com:xyz/demo.git']]])
      sh "git config user.name 'John Doe'"
      sh "git config user.email 'foo@bar.bla'"
    }
}

之后git commit应该工作。除非您想推送提交,否则您可以删除withCredentials包装器。


推荐阅读