如何在 github 组织 Jenkins 工作流程中检出 ssh 远程并在 Jenkinsfile 中使用 ssh 凭据

How to checkout ssh remote in github organization Jenkins workflow and use ssh credentials in Jenkinsfile

我在 jenkins 中有一个 Github Organisation 项。在我存储库的根目录中,我的 Jenkinsfile 看起来像这样:

node {

  def jenkinsCredsId = 'xxxxxxxx-yyyy-zzzz-aaaa-bbbbbbbbbbbb'

  stage 'Checkout'
  checkout scm
  // I also tried the following:
  // checkout scm: [$class: 'GitSCM', source: 'ssh://git@github.com:MY_ORGANISATION/jenkins-testing-temp.git', clean: true, credentialsId: jenkinsCredsId]

  stage 'Build'
  // generate some artefact (dist.zip)

  stage 'Release'

  sshagent([jenkinsCredsId]) {
    sh '''
    git remote -v // show remotes
    ssh-add -l // show currently loaded ssh keys fingerprints

    git fetch --all --tags // IT FAILS HERE

    CURRENT_BUILD_TAG="some_build/${BUILD_NUMBER}"
    git tag ${CURRENT_BUILD_TAG}

    git push --tags

    github-release release \
    --security-token ${GITHUB_RELEASE_TOKEN} \
    --user MY_ORGANIZATION \
    --repo MY_REPO \
    --tag ${CURRENT_BUILD_TAG} \
    --name ${CURRENT_BUILD_TAG}

    github-release upload \
    --security-token ${GITHUB_RELEASE_TOKEN} \
    --user MY_ORGANIZATION \
    --repo MY_REPO \
    --tag ${CURRENT_BUILD_TAG} \
    --name ${CURRENT_BUILD_TAG} \
    --file dist.zip
    '''
  }

此处有几行用于测试存储库访问,它目前在 git fetch 部分 失败,出现以下错误:

fatal: could not read Username for 'https://github.com': No such device or address

上面的 git remote -v 命令 Jenkinsfile 输出类似于 origin https://github.com/MY_ORGANIZATION/MY_REPO.

我的 Github Organization git 配置如下所示:

我发现了几个相关问题:

事实证明,Github Organization 项仅使用 Scan credentials 的 https 凭据(如上图)。

解决方案是点击 Advanced 按钮,并在 Checkout credentials 下拉列表中实际 select 一个 ssh 凭据,而不是默认的 - Same as scan credentials -

请注意,带星号的凭据是 user/password 个条目,这就是我发现问题的方式。

这样,checkout scm 将改用 ssh,而 sshagent([jenkinsCredsId]) { 块将按预期工作,让您根据自己的权限创建标签、获取和推送。 :)