How to set up deployment keys for multiple Jenkins projects

If you are using Jenkins to build multiple projects and you have tried using deployment keys, you will have noticed that you need a new deployment key for each project in services such as GitHub and BitBucket.  This creates a difficulty when configuring your Jenkins builds, because the jenkins user always pulls with the same SSH key.

There is a pretty easy solution to this, but I always seem to trip up when implementing it on a new server, so here it is, step by step.

1. Create deployment keys for your projects (don’t use a passphrase)

ssh-keygen -t rsa -f /var/lib/jenkins/.ssh/id_rsa_MY_FIRST_PROJECT
ssh-keygen -t rsa -f /var/lib/jenkins/.ssh/id_rsa_MY_SECOND_PROJECT

Ensure that your keys are owned by the jenkins user.

2. Add the public part of each key pair to its associated project

Login to your GitHub/BitBucket/Other account, then, for each repository find the Deployment Keys area and add the public part of your key pair for that repository.

3. Create an SSH config file in the jenkins user’s ~/.ssh directory

sudo vi /var/lib/jenkins/.ssh/config

4. In this file, add an entry for each project, such as those below

Host github-my-first-project
HostName bitbucket.org
User git
IdentityFile ~/.ssh/id_rsa_MY_FIRST_PROJECT

Host github-my-second-project
HostName bitbucket.org
User git
IdentityFile ~/.ssh/id_rsa_MY_SECOND_PROJECT

This has created per-project domain aliases for, in this case, bitbucket.org, with each domain alias being associated with its own private key.

5. Log in as the jenkins user and force the creation of the known hosts file

sudo su -l -p jenkins
ssh git@bitbucket-my-first-project

6. You can now set up your jenkins to pull from your repositories as

git@bitbucket-my-first-project:Username/my-first-project.git
git@bitbucket-my-second-project:Username/my-second-project.git

{ 1 comment… add one }

  • Cecelia Z. Hatfield July 6, 2013, 5:41 am

    I don’t really understand why each deployment key has to be uniqe. We use jenkins to build all our projects and jenkins has only one public ssh-key. Thus we have to create a virtual user (jenkins) in GitLab and give it access to repositories, because each deployment key has to be uniqe.

    Reply

Leave a Comment