Skip to content

Instantly share code, notes, and snippets.

@neilmayhew
Created December 16, 2021 18:26
Show Gist options
  • Save neilmayhew/8d0da43340c48a7156e1530b225962f0 to your computer and use it in GitHub Desktop.
Save neilmayhew/8d0da43340c48a7156e1530b225962f0 to your computer and use it in GitHub Desktop.
Configuring git to use a different GitHub/GitLab identity for some projects

Using a different GitHub/GitLab account for some projects

If you're working on a project that requires you to use a separate account on GitHub/GitLab, it can be a bit tricky to set up. Your ssh key identifies you uniquely, so you can't use the same key for two different accounts. However, git doesn't have a simple way for you to configure an ssh key for a repo or a group of repos. You have to do it by creating an alias for the host name and associating a different key with that host name. Here's one way to do it.

Note: Replace all instances of something with the project or client name.

Create a new ssh key

ssh-keygen -f ~/.ssh/id_rsa-something [other-options]

Add a hostname alias

In ~/.ssh/config:

# Something - use the special key
Host something.gitlab.com
  Hostname gitlab.com
  IdentitiesOnly yes
  IdentityFile ~/.ssh/id_rsa-something
# Everything else - use the default keys only
Host gitlab.com
  IdentitiesOnly yes
Host github.com
  IdentitiesOnly yes

Add a conditional include

In ~/.config/git/config:

[includeIf "gitdir:~/path/to/something/"]
  path = something.inc

This assumes all your repos for the project/client are in a single directory hierarchy.

Configure use of the alias

In ~/.config/git/something.inc:

[url "[email protected]:something/"]
  insteadOf = [email protected]:something/
[user]
  email = [email protected]

If you don't need a separate email address, you can put the url.<>.insteadOf directly into the main git configuration file. However, it's very useful to be able to add other project-specific settings as well, so having the separate include is worthwhile.

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