manage 2 git users gpg key and choose gpg sign per user

5.3k views Asked by At

I have 1 github user and another gitlab user, and I have created 1 gpg key for each because my email address differs.

The problem is I have to execute git config --global user.signingkey everytime I want to commit to different git repos.

Is there a way I can manage my gpg keys per git user?

4

There are 4 answers

5
chakrit On BEST ANSWER

I have the same situation but with splitting of work/personal accounts. And I have a lot of repositories but I don't want to run git config every time I clone something new.

I have written a blog post about it. A way to do this automatically is to use the includeIf directive provided by git. You can read more about it from the Conditional Include section in git manual.


There's a small requirement tho, you need to be able to tell apart github repositories from your GitLab repositories by a component in your path (for example, put GitHub clones in ~/github and Gitlab clones in ~/gitlab)

Then, basically, split the signing key configuration into two files:

# config.github
[user]
  name       = Chakrit
  email      = [email protected]
  signingkey = DEADBEEF

# config.gitlab
[user]
  name       = Chakrit
  email      = [email protected]
  signingkey = BADC0FFEE

And then in your main ~/.config/git/config configuration file, use the includeIf gitdir: directive to match and include different files based on your WD:

# when working with github
[includeIf "gitdir:**/github/**/.git"]
  path = config.github

# when working with gitlab
[includeIf "gitdir:**/gitlab/**/.git"]
  path = config.gitlab

Then all repos in your ~/github folder will automatically use your GitHub key and repos in your ~/gitlab folder will use your GitLab keys.

0
sphakka On

I'd improve @chakrit's answer, but the edit queue is full since a while...

I prefer a file-system-agnostic approach and load the correct configuration based on the remote Git host URL:

[includeIf "hasconfig:remote.*.url:**/github.com*/**"]
    path = config.github
3
Casper On

Just remove all user.signingkey settings from your repo and your global settings.

git will decide to use a key ingpg with a matching identity for the user.email setting from your repo.

1
james On

The signingkey may be set per-repository, just execute: git config user.signingkey from within a checked out repository. This command sets the configuration in the repositor's .git/config. The --global options causes the config to be written into ~/.gitconfig where it becomes the default for repositories that do not have a local value set.

More information can be found in git-config's man page in the user.signingKey section.

You may also get better results by also setting user.email to the email associated with the repository.