Skip to content

Instantly share code, notes, and snippets.

@devzom
Forked from jmcaldera/ssh_multikeys.md
Last active September 25, 2021 07:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devzom/1c44e1badbf9a97ae89d39d5bb5acc58 to your computer and use it in GitHub Desktop.
Save devzom/1c44e1badbf9a97ae89d39d5bb5acc58 to your computer and use it in GitHub Desktop.
Multiple SSH Keys macOS

Multiple SSH Keys on same client

Check if you have existing keys by opening the terminal and entering: ssh-add -l OR ls -al ~/.ssh and check for any file called (usually) id_rsa or similar

Identify the host you're using your current key for. You probably added this key to, for example your github or gitlab account. We will use this later on.

If you don't have a config file on ~/.ssh folder, you will need to create one. We'll get back to this later.

Now create a new key for your new host by following the steps on https://docs.github.com/en/github/authenticating-to-github/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent and give it a different name, like id_rsa_github_personal.

Once you've created a new key, it's time to create our config file (or modify if you have one already) at ~/.ssh/config. Type nano config and add the following lines:

# GitHub Personal
Host github_personal
HostName github.com
AddKeysToAgent yes
UseKeyChain yes
IdentityFile ~/.ssh/id_rsa_github_personal

If you didn't have a config file but did have a key, now is the time to add it to the file. Let's say that you were using it for your company's github repository, so just add the following lines (edit it accordingly):

# GitHub Company
Host github_company
HostName github.com
AddKeysToAgent yes
UseKeyChain yes
IdentityFile ~/.ssh/id_rsa

Note: you should add the correct file name to IdentityFile.

Now it's time to add your key to the ssh-agent: Start the agent if you haven't already by running eval "$(ssh-agent -s)", then enter ssh-add -K ~/.ssh/id_rsa_github_personal. And you're all set!

Note: if on the first step the output for ssh-add -l was "The agent has no identities" but you did found a key on /.ssh folder, then add that key to the agent.

So now when you want to clone a repository using ssh, the url is usually in this format: git@github.com:username/repository-name.git. You will need to modify github.com and use the Host name that you added to config file. For example: git@github_company:username/repository-name.git. or git@github_company/repository-name.git if you don't need the username to provide ex.: as repositorium is public on VPN

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment