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
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
6. You can now set up your jenkins to pull from your repositories as