Friday, June 22, 2018

Authenticating with deploy keys in Jenkins pipelines

While using M$ github you may use deploy keys dedicated to a specific repository instead of giving your private key to Jenkins. And yes, it is possible to use deploy key in Jenkins pipelines.

To be able to manage your ssh identity you need first to install sshagent plugin.

BTW If you are running Jenkins instance on M$ windows machine remember to add sshagent (eg. from your git distribution) to your %PATH%.

Generate a key pair.
ssh-keygen -t rsa -b 4096 -C ""

Goto Credentials in Jenkins left-side main menu. Add credentials of type 'SSH Username with private key'. You can paste the created private key into text area.

In M$ github repository settings now you can add corresponding public key.

In your pipeline code you can use credentials when you surround eg. git calls with sshagent block.

                sshagent(credentials: ['throw-me-away-key']) {
                    bat """git pull origin master"""

If you get errors make sure that you are not using friendly name but right ID of credential in Jenkins.

10:09:04 FATAL: [ssh-agent] Could not find specified credentials
10:09:04 [ssh-agent] Looking for ssh-agent implementation...
10:09:04 [ssh-agent]   Exec ssh-agent (binary ssh-agent on a remote machine)
10:09:04 $ ssh-agent
10:09:04 SSH_AUTH_SOCK=/tmp/ssh-vCKYmwW5gfvP/agent.5592
10:09:04 SSH_AGENT_PID=5572
10:09:04 [ssh-agent] Started.
10:09:04 [original] Running batch script
10:09:04 C:\Program Files (x86)\Jenkins\workspace\lk-pipeline-0\original>git pull 
10:09:06 $ ssh-agent -k
10:09:06 Permission denied (publickey).
10:09:06 fatal: Could not read from remote repository.
10:09:06 Please make sure you have the correct access rights
10:09:06 and the repository exists.
10:09:06 unset SSH_AUTH_SOCK;
10:09:06 unset SSH_AGENT_PID;
10:09:06 echo Agent pid 5572 killed;
10:09:06 [ssh-agent] Stopped.

1 comment:

  1. Using right ID of credential in Jenkins is the key of this problem, when I gave an ID to the key, it didn't work, while I deleted it after I read through this article, and used the generated ID, it works now!