Github is incredibly popular 'Git repository hosting service'1, where over 83 million developers (by their own admission) choose to store their code. This level of popularity easily lands Github in the industry standard category of software development tooling.
If you've used github for more than a few years, you probably remember when November 13, 2020 rolled around and Github discontinued password authentication. This took me a few weeks to understand how the heck I'm supposed to push my code But that's what we are here to overcome.
Now of course, you could take the OAth approach but then you have to store that token, keep updating when it expires, etc. But I'm here to show you a still more excellent way, SSH Keys
Github provides an excellent walk through on how to setup github and your local git cli with a ssh key. Which, I've read multiple times, and followed step by step to great success. What it does not show is how to handle multiple ssh keys for authenticating with more than one repo.
This is actually much easier than it might sound. But a little background is necessary first. When you configure your git cli with a SSH Key, you are actually giving a ssh-agent a specific private key. Git then leverages the ssh-agent to authenticate you. What we need to do, is tell git to use a specific key when you are using git from a specific directory.
We will need to edit the ~/.gitconfig, open this file with your favorite text editor (mine is vi). Here is where the magic happens. Similarly to how you originally configured your ssh-agent, we are going to setup git to run a sshCommand depending on your current directory. Lets start with the
Before we begin, you need to have both private ssh keys saved somewhere. Then you need to create a new config file, something like .gitconfig-company1 and add this to it.
...
[core]
sshCommand = ssh -i ~/.ssh/path_to_your_key
...
You can create however many of these you want! Go wild. Next we need to setup git to use these specific config files depending on a path. Luckily, git makes that easy.
...
[includeIf "gitdir:/directory1/"]
path = .gitconfig-company1
[includeIf "gitdir:/directory2/"]
path = .gitconfig-company2
...
Note, the includeIf
just needs the root path, it will apply this configuration to anything nested in the directory provided.