147

I was following this tutorial:

node {
  git url: 'https://github.com/joe_user/simple-maven-project-with-tests.git'
  ...
}

However it doesn't tell how to add credentials. Jenkins does have specific "Credentials" section where you define user user&pass, and then get ID for that to use in jobs, but how do I use that in Pipeline instructions?

I tried with:

git([url: 'git@bitbucket.org:company/repo.git', branch: 'master', credentialsId: '12345-1234-4696-af25-123455'])

no luck:

stderr: Host key verification failed.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

Is there a way configure the creds in pipeline, or do I have to put SSH-keys to Jenkin's Linux user's .ssh/authorized_keys file?

In ideal world I'd like to have a repository for pipeline jobs and repo-keys, then launch Docker Jenkins, and dynamically add these jobs and keys there without having to configure anything in Jenkins Console.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Render
  • 2,199
  • 2
  • 16
  • 14

6 Answers6

219

You can use the following in a pipeline:

git branch: 'master',
    credentialsId: '12345-1234-4696-af25-123455',
    url: 'ssh://git@bitbucket.org:company/repo.git'

If you're using the ssh url then your credentials must be username + private key. If you're using the https clone url instead of the ssh one, then your credentials should be username + password.

the_storyteller
  • 2,335
  • 1
  • 26
  • 37
Serban Constantin
  • 3,316
  • 1
  • 18
  • 20
  • 2
    That fixed it, thank you. I wasn't aware that SSH-url and HTTPS-url require different credentials to work with! – Render Jul 19 '16 at 18:13
  • 7
    it was helpful, but `credentialsId` comes from id in [`/var/lib/jenkins/credentials.xml`](https://stackoverflow.com/a/35603191/432903) as I had to struggle to figure it out. – prayagupa Jun 01 '17 at 08:26
  • 26
    @prayagupd, you should be able to get the credential ID from the credentials page (`http://yourjenkinsinstall/credentials`). No need to trawl the config files. – Serban Constantin Jun 06 '17 at 13:49
  • what if I wish to use private and public key? is there any way to use my jenkins keys? – Ori Wiesel Oct 30 '17 at 13:14
  • 3
    Do you know if it's possible to re-use credentials defined in a job? – Kentzo Dec 16 '17 at 03:55
  • how to generate this credentialsId? – undefined Jul 06 '18 at 10:35
  • 6
    For those who ask "How to Generate a credentialsId". Here how to find it. [1. Click on Credentials on Jenkins homepage, 2. You will then see a table with all the credentials you created. 3. ID is in this table] – vincedjango Sep 07 '18 at 20:29
  • 1
    For me it couldn't resolve the URL when I set it to start with `ssh://`. Removing it, fixed it. – Moshisho Sep 26 '19 at 09:58
  • All these answers, and nobody links to the documentation for Jenkin's `git` command? – cowlinator Dec 19 '19 at 00:47
  • It worked for me, but I had to remove the ssh:// of the URL – David Marciel Mar 23 '20 at 16:51
  • No need to use `ssh://` in url – Gaurav Khare Aug 16 '20 at 19:25
  • It doesn't work for me.... WorkflowScript: 14: Invalid parameter "branch", did you mean "name"? @ line 14, column 21. git branch: 'staging' – Jose Luis Estevez Feb 12 '21 at 11:19
  • If we use bitbucket, we can also create a consumer key to substitute username and password. `Key = Username`, `Secret = Password` https://support.atlassian.com/bitbucket-cloud/docs/use-oauth-on-bitbucket-cloud/#OAuthonBitbucketCloud-Createaconsumer – Wildan Muhlis Apr 01 '21 at 01:30
  • Thanks, this helped me as well. I was struggling to checkout in single pipeline mode. – Deepthi Jun 13 '23 at 08:49
59

To explicitly checkout using a specific credentials

    stage('Checkout external proj') {
        steps {
            git branch: 'my_specific_branch',
                credentialsId: 'my_cred_id',
                url: 'git@test.com/proj/test_proj.git'

            sh "ls -lat"
        }
    }

To checkout based on the configured credentials in the current Jenkins Job

    stage('Checkout code') {
        steps {
            checkout scm
        }
    }

You can use both of the stages within a single Jenkins file.

ACV
  • 9,964
  • 5
  • 76
  • 81
Upul Doluweera
  • 2,146
  • 1
  • 23
  • 28
  • 2
    how to generate this credentialsId? – undefined Jul 06 '18 at 10:34
  • 2
    have a look - https://support.cloudbees.com/hc/en-us/articles/203802500-Injecting-Secrets-into-Jenkins-Build-Jobs – Upul Doluweera Jul 07 '18 at 12:31
  • where should i store the credentials file. jenkins sais : Warning: CredentialId "jenkins_key" could not be found. – Dinu Nicolae Jul 19 '19 at 09:42
  • @Dinu credentials are created in Jenkins, you should see it in the main menu if the plugin in installed. https://support.cloudbees.com/hc/en-us/articles/203802500-Injecting-Secrets-into-Jenkins-Build-Jobs – Upul Doluweera Jul 22 '19 at 03:45
  • Thank you, this is most useful – Alexander Jan 10 '20 at 17:39
  • 1
    thank you! someone who posted the entire thing rather than just a bit here and bit here, and hoping people magically know what to put for the rest of it. –  Feb 04 '20 at 17:24
38

Adding you a quick example using git plugin GitSCM:

    checkout([
        $class: 'GitSCM', 
        branches: [[name: '*/master']], 
        doGenerateSubmoduleConfigurations: false, 
        extensions: [[$class: 'CleanCheckout']], 
        submoduleCfg: [], 
        userRemoteConfigs: [[credentialsId: '<gitCredentials>', url: '<gitRepoURL>']]
    ])

in your pipeline

stage('checkout'){
    steps{
        script{
            checkout
        }
    }
}
avivamg
  • 12,197
  • 3
  • 67
  • 61
  • do you know how to use a global credentials for the entire team? Or is there a way so that whichever developer is pushing to github, they can provide their credentials without having to expose it in the Jenkinsfile – henhen Mar 24 '20 at 05:15
  • You can manage your mechanism related to your own logic in your dev team, and use different credentials keys for each group. for example: If a Github user is in list of 'backend_developers' use , If Github user in list of 'frontend_developers' use ,design your mechanism related to your own use case. – avivamg Mar 24 '20 at 07:34
  • where would you keep these credentials? Is it with the Jenkins Credentials plugin? – henhen Mar 24 '20 at 17:18
  • Use Jenkins credentials documentation - https://jenkins.io/doc/book/using/using-credentials/ – avivamg Mar 24 '20 at 18:37
  • 4
    I’ve searched far and wide for a simple `checkout` example like this one, thank you. – 301_Moved_Permanently Apr 28 '20 at 09:37
  • where does this `checkout` function go in the Jenkinsfile? – Parag Kadam Aug 09 '22 at 11:06
  • import at as "shared-library" ( `@Library('my-shared-library') _` ) from another repository and connect this library on jenkins configuration as well with the right source control access permissions: Use this link for more info: https://www.jenkins.io/doc/book/pipeline/shared-libraries/ – avivamg Aug 09 '22 at 20:38
31

If you want to use ssh credentials,

  git(
       url: 'git@github.com<repo_name>.git',
       credentialsId: 'xpc',
       branch: "${branch}"
    )

if you want to use username and password credentials, you need to use http clone as @Serban mentioned.

    git(
       url: 'https://github.com/<repo_name>.git',
       credentialsId: 'xpc',
       branch: "${branch}"
    )
Benoit Wickramarachi
  • 6,096
  • 5
  • 36
  • 46
f-society
  • 2,898
  • 27
  • 18
  • 10
    how to generate this credentialsId? – undefined Jul 06 '18 at 10:34
  • I generated the credentials like this: https://help.github.com/en/articles/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent, I added the public key to my git, but where do I have to store this file. Jenkins says: Warning: CredentialId "jenkins_key" could not be found. – Dinu Nicolae Jul 19 '19 at 09:39
  • @DinuNicolae please refer `Adding new global credentials -> 7.` at following link.https://jenkins.io/doc/book/using/using-credentials/ – f-society Jul 21 '19 at 08:40
  • Nice Answer. upvote you. `git(..)` clones remote repository. How can I commit & push current working directory to certain repository, certain branch. I have credenitalsId to target repository. – Denis Turgenev Jul 10 '21 at 11:35
5

For what it's worth adding to the discussion... what I did that ended up helping me... Since the pipeline is run within a workspace within a docker image that is cleaned up each time it runs. I grabbed the credentials needed to perform necessary operations on the repo within my pipeline and stored them in a .netrc file. this allowed me to authorize the git repo operations successfully.

withCredentials([usernamePassword(credentialsId: '<credentials-id>', passwordVariable: 'GIT_PASSWORD', usernameVariable: 'GIT_USERNAME')]) {
    sh '''
        printf "machine github.com\nlogin $GIT_USERNAME\n password $GIT_PASSWORD" >> ~/.netrc
        // continue script as necessary working with git repo...
    '''
}
madeyejm
  • 472
  • 3
  • 14
4

It solved for me using

checkout scm: ([
                    $class: 'GitSCM',
                    userRemoteConfigs: [[credentialsId: '******',url: ${project_url}]],
                    branches: [[name: 'refs/tags/${project_tag}']]
            ])
David Buck
  • 3,752
  • 35
  • 31
  • 35
Sarang
  • 422
  • 5
  • 11