Search code examples
gitgpg-signature

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


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?


Solution

  • 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      = github@example.com
      signingkey = DEADBEEF
    
    # config.gitlab
    [user]
      name       = Chakrit
      email      = gitlab@example.com
      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.