How to specify different SSH keys for git push for a given domain
There are some cases when you want to use a different SSH key to push to a given git repo. For example, you want to push a local repo located on your production server to a git server (maybe on a different host), but the default ~/.ssh/id_rsa
is the server's deployment key, which does not allow you to push (it's a read-only key).
Note: if you don't have any SSH keys yet, see the last section of this post for the guide how to generate one.
In such cases, when the user and hostname are the same, you can specify a different SSH key with write permission in your ~/.ssh/config
file. For example, if your configuration looks like this:
Host github-as-thuc
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa.thuc
IdentitiesOnly yes
Host github-as-ten
HostName github.com
User git
IdentityFile /home/ten/.ssh/id_dsa.ten
IdentitiesOnly yes
Then you just use github-as-thuc
and github-as-ten
instead of the real hostname (git.thuc.com
) in your URL:
git remote add thuc git@github-as-thuc:your-repo.git
git remote add ten git@github-as-ten:your-repo.git
Note
The option IdentitiesOnly yes
is included to prevent the use of default identities. Otherwise, if you also have identity files matching the default names, they will get tried first because unlike other config options (which abide by "first in wins") the IdentityFile
option appends to the list of identities to try. See: http://serverfault.com/questions/450796/how-could-i-stop-ssh-offering-a-wrong-key/450807#450807
Bonus 1: How to generate new SSH key pair
- Open terminal and paste the following command (replace your own email):
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
2. Enter the file location and passphrase as requested, and you’ve done.
$ ssh-keygen -t rsa -b 4096 -C "thucnguyen@domain.com"
Generating public/private rsa key pair.
Enter file in which to save the key (/home/thuc/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/thuc/.ssh/id_rsa.
Your public key has been saved in /home/thuc/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:Hora+7+HjdM0epSeOvjVug2+DdHzDUywnXjvM+wJqU4 thuc.nc@domain.com
The key's randomart image is:
+---[RSA 4096]----+
| . |
| = . |
| o = |
| . + . |
| S ..o o .|
| . o .=o XX+ |
| . ...X+E.o.+o|
| o . *oO*. o +|
| . oo.o=B*=o o |
+----[SHA256]-----+
Bonus 2: How to generate public key from existing private key
ssh-keygen -y -f ~/.ssh/id_rsa > ~/.ssh/id_rsa.pub