Search code examples
gitgithubsshgitlabssh-keys

Using Github and Gitlab


My Problem

I wanted to do commits on Github with my private email a@gmail.com and commits to our companys Gitlab with the company email me@company.com, without changing the config of Git with every commit. So when I do commits on Github, it's linked to my Github-account and the same for Gitlab.

What I already made

Therefore I've created two different SSH keys and connected them with Github and Gitlab. I also have a file called config in my folder ~/.ssh/ with this in it:

Host github.com
    HostName github.com
    IdentityFile ~/.ssh/github
    IdentitiesOnly yes
    User KonstantinSchuette

Host gitlab.company.com
        HostName gitlab.company.com
        IdentityFile ~/.ssh/gitlab
        IdentitiesOnly yes
        User KonstantinSchuette

But my commits are not connected to the account that I've linked the keys to.


Solution

  • What I misunderstood

    I thought that SSH keys are used to make commits with different accounts on Github and Gitlab, so that it overrides the config. But thats not the case. They are only used to get access from different accounts to different platforms, without typing in the credentials of an account.

    Solution

    I needed to create different folders for Github and Gitlab to load a different config for Git, when I'm working on Github and Gitlab projects at the same time. So only repositorys from Github are in the Github-folder and only Gitlab repositorys are in the Gitlab-folder.

    I edited my ~/.gitconfig to that:

    [includeIf "gitdir/i:~/Desktop/Github/"]
      path=.gitconfig-Github
    [includeIf "gitdir/i:~/Desktop/Gitlab/"]
      path=.gitconfig-Gitlab
    

    And in the same directory as the .gitconfig i created the .gitconfig-Github:

    [user]
    name=Dewey
    email=a@gmail.com
    

    and also a .gitconfig-Gitlab:

    [user]
    name=Dewey
    email=me@company.com
    

    I'm using VSCode so it was essential that the includeIf starts with gitdir/i: to turn off case-sensitive. If you don't do this step your config will not be loaded when you use VSCode.

    I've found the solution to that on the issue board for VSCode: https://github.com/Microsoft/vscode/issues/62921

    Now everything works as I wanted it to.