Using multiple ssh keys in different git projects and accounts
SSH besides standard configuration where we define what host uses which key and user can have advanced features. Let’s check the feature that allows to specify different ssh keys for the same host (github.com) but for different projects and users.
Generate SSH keys add them to you local machine and to remote git server
This is standard flow, check this post for full details: Sign git commits with GPG key
Update ~/.ssh/config:
Let’s say we have 2 users, that have different github accounts:
- superhacker
- admin
For both of them we need to create 2 section in ssh config, the difference is that after defining the hostname we also define a username.
Based on this username configure at github repo, appropriate ssh key will be used for ssh protocol when working with git
1
2
3
4
5
6
7
8
9
10
11
Host github.com-superhacker
User git
Hostname github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/github_superhacker_rsa
Host github.com-admin
User git
Hostname github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/github_admin_rsa
Add ssh keys to local agent
1
2
$ ssh-add ~/.ssh/github_superhacker_rsa
$ ssh-add ~/.ssh/github_admin_rsa
Test connection
1
2
3
4
$ ssh-keyscan github.com
$ ssh-keyscan github.com >> ~/.ssh/known_hosts
$ ssh -T git@github.com-superhacker
$ ssh -T git@github.com-admin
Working with 1st repo:
1
2
3
$ git clone git@github.com:superhacker/project1.git
$ git config user.name "superhacker"
$ git config user.email "superhacker@gmail.com"
Other option:
1
2
[remote "origin"]
url = git@github.com-superhacker:superhacker/project1.git
Same content is shown in .git/config in project folder
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
ignorecase = true
precomposeunicode = true
[remote "origin"]
url = git@github.com:superhacker/project1.git
fetch = +refs/heads/*:refs/remotes/origin/*
[branch "main"]
remote = origin
merge = refs/heads/main
[user]
name = superhacker
email = superhacker@gmail.com
All commits of this repo will be done under user superhacker and signed with key github_superhacker_rsa
Workings with 2nd repo:
1
2
3
$ git clone git@github.com:admin/project1.git
$ git config user.name "admin"
$ git config user.email "admin@gmail.com"
Same content is shown in .git/config in project folder
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
ignorecase = true
precomposeunicode = true
[remote "origin"]
url = git@github.com:admin/project1.git
fetch = +refs/heads/*:refs/remotes/origin/*
[branch "main"]
remote = origin
merge = refs/heads/main
[user]
name = admin
email = admin@gmail.com
All commits of this repo will be done under user admin and signed with key github_admin_rsa