Using multiple ssh hosts
Using multiple ssh hosts for git
When you want to use multiple git hosts (e.g. multiple github accounts or codeberg etc.) on the same machine you need to alias the host so git knows which keys to try.
So one way to this is how this stackoveflow answer says: (the steps are skipping the ceremony around creating a new ssh key-pair)
- set an alternative host in your default ssh config file
Host github2.com - use that in your git commands like this:
git clone git@github2.com:user/repo.git
This works, but I am not really a fan of using different commands and remembering these. I already use some gitconfig trickery to use overlays based on the file system path, that I am currently working in, so here is how you can do this in a more complicated, but -- in my opinion -- a cleaner way, where unrelated configs are not in a single file.
- set up an alternative ssh config file
.ssh/config-github2
Host github2 github.com
AddKeysToAgent yes
PreferredAuthentications publickey
IdentityFile ~/.ssh/github2
IdentitiesOnly yes
- you can test this config file before proceeding with the set-up:
ssh -F ~/.ssh/config-github2 -T git@github.com - set up the per path config with git config includes. Create
~/.gitconfig-github2:
[user]
email = my-mail@no-reply.com
name = tmon xyz
[core]
sshCommand = ssh -F /Users/TIVI/.ssh/config-github2
- include this file based on the fs path:
[includeIf "gitdir:~/other-projects/"]
path = .gitconfig-github2
- Now if you
cd ~/other-projectsand try to clone a private repo from yourgithub2account it should just work, with the vanilla ssh command and the complexity is hidden from everyday use.
Why complicate things to this matter?
If you work with on-prem infra or for some other reason ssh into a fair amount of remote machines e.g. to check on your little AI helpers running in a remote environment, you might end up 10+ ssh hosts in a single config file. This really quickly becomes hard to manage with a single ssh config file.
If you use multiple git hosts, it also makes sense to use multiple config files. I have used Gitlab, Github and Azure Repositories professionally. Right now I am using Github 100%, but this might change.