Automate Git Authentication with SSH
You have an account on GitHub and Bitbucket,
and you want to access both accounts using SSH keys without interaction.
Create the keys
Create keys for each domain.
mkdir -p ~/.ssh
cd ~/.ssh
# create keys with Ed25519
ssh-keygen -t ed25519 -f ~/.ssh/github -C "jano@jano.com.es"
ssh-keygen -t ed25519 -f ~/.ssh/bitbucket -C "jano@jano.com.es"
# add them to the keychain
eval "$(ssh-agent -s)"
ssh-add --apple-use-keychain ~/.ssh/github
ssh-add --apple-use-keychain ~/.ssh/bitbucket
# list all
ssh-add -l
Finder doesn’t show directories that start with a dot, but you can toggle the visibility of hidden files in Finder, click ⌘⇧. (that’s shift + command + dot).
Add them to your account
Copy the public keys and paste them on GitHub and on Bitbucket.
pbcopy < ~/.ssh/bitbucket.pub
pbcopy < ~/.ssh/github.pub
Configure SSH
Add the path to the private key to the keychain
ssh-add -K ~/.ssh/bitbucket
ssh-add -K ~/.ssh/github
Open the configuration file (mate is my editor).
mate ~/.ssh/config
Paste the following content in ~/.ssh/config:
Host bitbucket.org
User git
Hostname bitbucket.org
PreferredAuthentications publickey
IdentityFile ~/.ssh/bitbucket
Host github.com
User git
Hostname github.com
PreferredAuthentications publickey
IdentitiesOnly yes
IdentityFile ~/.ssh/github
If you ever need a second user for the same host, add it with a different hostname. For instance, let’s say I have a second user janopokemon
that works in the Pokemon company and I need to clone the repo at https://github.com/pokemon/GottaCatchThemAll.
Host github.com-janoPokemon
User git
Hostname github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/janopokemon
And specify the host when you add the remote origin of the repo:
git remote set-url origin git@github.com-janopokemon:pokemon/CatchThemAll.git
Test the keys
Type the following to check that your GitHub setup authenticates correctly:
ssh -T git@github.com
ssh -T git@bitbucket.org
At this point you can clone projects from the terminal using the git protocol:
git clone --recursive git@github.com:mycompany/myproject.git
When cloning a repository, use the ssh: addresses. If you use the https: addresses you will be asked for user/password. For instance, let’s say you clone with ssh but the project has submodules declared with http. You can still automate this using an access token and a .netrc file. I’ll write about this next.