0

The github key is stored in Jenkins. Now I have a Jenkins job that uses the withCredentials plugin to get that private key like this:

withCredentials([sshUserPrivateKey(credentialsId: "my-cred-id", keyFileVariable: 'key')]) {
    //auth to git here then do some commands for example:
    sh 'git commmit -am "hello my commit message'
    sh 'git push'
}

Now what i want to do is within the withCredentials block to run a few git commands like the example shows above. However, i'm not sure how to use the keyFileVariable in order to authenticate to git so i can run these commands.

santino98
  • 145
  • 1
  • 2
  • 9

1 Answers1

2

Location of the SSH key is copied temporarily into the variable defined in keyFileVariable. In your case it is 'key'. You can access it by $key

Then you need to tell git to use the new credentials by setting the environment variable GIT_SSH_COMMAND = "ssh -i $key" So your step becomes:

withCredentials([sshUserPrivateKey(credentialsId: "my-cred-id", keyFileVariable: 'key')]) {
        //auth to git here then do some commands for example:
        sh 'git commmit -am "hello my commit message'
        sh 'GIT_SSH_COMMAND = "ssh -i $key"'
        sh 'git push'
    }

That being said, best practice is to setup the jenkins job once in the beginning and define the git key in repo settings. This is a fairly special use case where the checkout should not use the same credentials as the push.

Yamuk
  • 750
  • 8
  • 27
  • thank you @Yamac Kurtulus great answer, I do wonder about what you said with the best practice. Is it better to have a withCredentials with the single line sh 'GIT_SSH_COMMAND = "ssh -i $key"' at the start of the Jenkins job to authenticate the whole job? incase I need to do multiplie commands else in the job? – santino98 May 27 '21 at 06:23