Sometimes, we have multiple projects using different GitHub accounts and so, ssh keys. When come the moment to set and use a second account / ssh key, the first one will "always" be used by default. The solution is to configure ssh agent and then use it the right way with git commands.
Create a ssh key:
ssh-keygen -t ed25519 -C "[email protected]"
# Enter a file name (eg.: id_ed25519_work)
Start the user-agent before adding key:
eval "$(ssh-agent -s)"
# Agent pid 59566
Add the key to the user-agent:
ssh-add ~/.ssh/id_ed25519_work
Checking if the key is registered to the user-agent:
ssh-add -l
# 2048 6d:65:b9:3b:ff:9c:5a:54:1c:2f:6a:f7:44:03:84:3f [email protected] (ed25519)
Modifying ssh key file permissions:
# For public key: 644 (-rw-r--r--)
chmod 644 ./id_ed25519_work.pub
# For private key: 600 (-rw-------)
chmod 600 ./id_ed25519_work.pub
# Checking permissions octal level
stat -c "%a %n" *
Set up multiple ssh profiles by creating/modifying ~/.ssh/config
file:
Host github.com
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa
Host work.github.com
User workerName
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_ed25519_work
| Note the slightly differing Host
values
Verifying the ssh connection with the correct keys:
ssh -T [email protected]
# Hi <userName>! You've successfully authenticated, but GitHub does not provide shell access.
ssh -T [email protected]
# Hi workerName! You've successfully authenticated, but GitHub does not provide shell access.
| Note the correspondence between [email protected] and the .ssh/config
Host work.github.com
Now it's possible to clone a repository using a specific ssh config/key.
git clone [email protected]:userName/projectName.git
Solutions that will maybe works when there are multiple ssh keys, but only one account.
Ssh cloning by specifying the ssh key:
git clone -c core.sshCommand="/usr/bin/ssh -i ~/.ssh/id_ed25519_work" [email protected]:userName/projectName.git
Modifying an existing project by forcing a key to be used:
git config --local core.sshCommand "/usr/bin/ssh -i ~/.ssh/id_ed25519_work"