简体   繁体   中英

How to use Git Tokens in Jenkinsfile

I'm trying to use Jenkinsfile to clone git branches and merge them. 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. remote: You must use a personal access token or SSH key.

Does anyone know how to use git tokens from within jenkinsfile? I'd very much appreciate any help. Thanks

You should configure your personal access token or SSH key . Example for SSH key: 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. It's some kind of SSH Username with private key and the content is your SSH private key. Note the ID of the created credential.

Now you can fill your code above with 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.

Source - Jenkins Pipeline as code

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"    

  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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