Home > database >  Can I use two different Git with their respective SSH Key?
Can I use two different Git with their respective SSH Key?

Time:05-17

I have two different git accounts.

Account 1 GitHub [email protected]

Account 2 GitLab [email protected]

In my .ssh folder I have a SSH Key from my GitHub account. In the config file I have

Host *
   AddKeysToAgent yes
   UseKeychain yes
   IdentityFile ~/.ssh/id_edxxxxx

In my git config --global user.mail and name I have the GitLab account information.

My question is the following, how can I use both accounts with their respective SSH keys for different projects? Is it possible?

CodePudding user response:

I suggest generating a single SSH key and adding the public key it to both your GitLab and GitHub accounts. The emails you set for each local repo don't matter. These are only used to set on commits and have nothing to do with authentication with remote services.

CodePudding user response:

In my git config --global user.mail and name I have the GitLab account information.

This has nothing to do with authentication: you could have xxx and [email protected], that would be the same.

how can I use both accounts with their respective SSH keys for different projects?

That means two key:

  • the default one ~/.ssh/id_edxxxxx: its public key should be registered to user1
  • ssh-keygen -t ed25519 -P "" -f ~/.ssh/gh2: the gh2.pub should be regered to user2.

From there, add a ~/.ssh/config file with

Host gh1
User git
Port 22
Hostname github.com
IdentityFile ~/.ssh/id_ed25519
TCPKeepAlive yes
IdentitiesOnly yes

Host gh2
User git
Port 22
Hostname github.com
IdentityFile ~/.ssh/gh2
TCPKeepAlive yes
IdentitiesOnly yes

Replace your remote URL by:

cd /path/to/project1/local/clone
git remote set-url origin gh1:User1/project1

cd /path/to/project2/local/clone
git remote set-url origin gh2:User2/project2

That way, "both accounts with their respective SSH keys for different projects".

  • Related