Checkout Jenkins Pipeline Git SCM with credentials

2019-03-08 06:57发布

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.

4条回答
爷、活的狠高调
2楼-- · 2019-03-08 07:34

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.

查看更多
Explosion°爆炸
3楼-- · 2019-03-08 07:43

To explicitly checkout using a specific credentials

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

            sh "ls -lat"
        }
    }

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

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

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

查看更多
孤傲高冷的网名
4楼-- · 2019-03-08 07:43

This is work for me 100% with jenkins script

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

        sh "ls -lat"
    }
}
查看更多
看我几分像从前
5楼-- · 2019-03-08 07:53

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}"
    )
查看更多
登录 后发表回答