简体   繁体   English

如何在 Jenkinsfile 中使用 Git 令牌

[英]How to use Git Tokens in Jenkinsfile

I'm trying to use Jenkinsfile to clone git branches and merge them.我正在尝试使用 Jenkinsfile 来克隆 git 分支并合并它们。 Skeleton code is as below:骨架代码如下:

pipeline {
    agent { 
        label ""
    }
    stages {
        stage("Git") {
            steps {
                git( url: , credentialsId: )
            }
        }
    }
}

Everytime I run this I get the error每次我运行这个我都会收到错误

stderr: remote: Password authentication is not available for Git operations. stderr: remote: Git 操作无法使用密码验证。 remote: You must use a personal access token or SSH key.远程:您必须使用个人访问令牌或 SSH 密钥。

Does anyone know how to use git tokens from within jenkinsfile?有谁知道如何在 jenkinsfile 中使用 git 令牌? I'd very much appreciate any help.我非常感谢任何帮助。 Thanks谢谢

You should configure your personal access token or SSH key .您应该配置您的personal access tokenSSH key Example for SSH key: https://help.github.com/en/github/authenticating-to-github/adding-a-new-ssh-key-to-your-github-account SSH 密钥示例: https : //help.github.com/en/github/authenticating-to-github/adding-a-new-ssh-key-to-your-github-account

Then go to Jenkins > Credential > add a new credential.然后转到 Jenkins > 凭据 > 添加新凭据。 It's some kind of SSH Username with private key and the content is your SSH private key.它是某种SSH Username with private keySSH Username with private key内容是您的 SSH 私钥。 Note the ID of the created credential.请注意所创建凭据的 ID。

Now you can fill your code above with credentialsId: <id-goes-here>现在,您可以使用credentialsId: <id-goes-here>填写上面的代码credentialsId: <id-goes-here>

When using a GitHub access token, you must use standard Username with password credentials, where the username is the same as your GitHub username and the password is your access token.使用 GitHub 访问令牌时,您必须使用标准用户名和密码凭据,其中用户名与您的 GitHub 用户名相同,密码是您的访问令牌。

Source - Jenkins Pipeline as code来源 - Jenkins 流水线即代码

Steps on how to create a personal access token - Creating a personal access token for the command line如何创建个人访问令牌的步骤 - 为命令行创建个人访问令牌

This worked for me:这对我有用:

  withCredentials([string(credentialsId: "GITHUB_TOKEN", variable: 'GITHUB_TOKEN')]) {
    // An example for getting the statuses for a commit using GITHUB_TOKEN:
    // Use env.GITHUB_TOKEN here or just let shell expand it...
    def statusJson = sh returnStdout: true, 
         script: "curl --fail -s -X GET -H 'Accept: application/vnd.github.v3+json' -u " +
          ":\$GITHUB_TOKEN " +
 "https://api.github.com/repos/myowner/myrepo/commits/$gitCommit/statuses"    

  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM