This is definitely a good place to start:
As for setting up multiple SSH identities, assume you have accounts with the following emails:
- GitLab ->
foxmascot@gmail.com - GitHub ->
octocat@gmail.com
First, you'd generate one key for your GitLab email:
$ ssh-keygen -t ed25519 -C "foxmascot@gmail.com"And then will be prompted to specify a file path
Generating public/private ed25519 key pair.
Enter file in which to save the key (/Users/your-name/.ssh/id_ed25519):You can either simply hit enter or if you’d like, specify it’s for GitLab: /Users/your-name/.ssh/id_ed25519_gitlab. For the sake of the rest of the example, we’re going to assume you opted for the default path and filename of /Users/your-name/.ssh/id_ed25519.
Then, generate another one for your GitHub email:
$ ssh-keygen -t ed25519 -C "octocat@gmail.com"But when prompted for a path this time, specify the path and append _github to the file:
Generating public/private ed25519 key pair.
Enter file in which to save the key (/Users/your-name/.ssh/id_ed25519): /Users/your-name/.ssh/id_ed25519_githubThis should create a bunch of files in the ~/.ssh/ folder:
id_ed25519id_ed25519_githubid_ed25519.pubid_ed25519_github.pub
To make sure that the correct ones are used for the corresponding domains, create a new (or edit the existing) file at ~/.ssh/config with at least the following:
Host gitlab
HostName gitlab.com
IdentityFile ~/.ssh/id_ed25519
Host github
HostName github.com
IdentityFile ~/.ssh/id_ed25519_github
And if you added them to your machine's keychain, you likely want to include these other options as well:
Host gitlab
UseKeychain yes
AddKeysToAgent yes
HostName gitlab.com
IdentityFile ~/.ssh/id_ed25519
Host github
UseKeychain yes
AddKeysToAgent yes
HostName github.com
IdentityFile ~/.ssh/id_ed25519_github
Finally, create new SSH key entries in your accounts (via GitLab, GitHub, etc.) using the content from each .pub file for its corresponding domain (for example, id_ed25519_github.pub for GitHub).
Adding this to your ~/.bash_profile (or ~/.zshrc) will automatically add the ssh keys to the keychain on your machine when you open a new terminal window or reload your profile
function addSshKeysToAgent {
# -K === --apple-use-keychain
# -A === --apple-load-keychain
/usr/bin/ssh-add --apple-use-keychain ~/.ssh/id_ed25519
/usr/bin/ssh-add --apple-use-keychain ~/.ssh/id_ed25519_github
}
function maybeStartSshAgentAndAddKeys {
# from https://stackoverflow.com/a/45841963
# if ps -p $SSH_AGENT_PID > /dev/null
if [ $(ps ax | grep [s]sh-agent | wc -l) -gt 0 ]
then
echo "ssh-agent is already running"
# Do something knowing the pid exists, i.e. the process with $PID is running
else
eval "$(ssh-agent -s)"
fi
addSshKeysToAgent
}
maybeStartSshAgentAndAddKeys