Saturday, October 23, 2021

[SOLVED] How to set git config to use specific key for domain?

Issue

How do you make a rule in your ~/.gitconfig to tell git to use a specific SSH key for a specific project?

I have separate personal and professional accounts on Gitlab, and I want to use my personal SSH key when committing to most of my Gitlab repos, but I want to specify a separate key when committing to my professional Gitlab repos. Aside from keeping things neat and tidy, this is also required from a technical standpoint as Gitlab doesn't let you share SSH keys between two accounts.

Searching for this situation, I found numerous solutions, such as appending this to my ~/.gitconfig:

[includeIf "gitdir:~/git/my_professional_project/"]
    [user]
        email = "[email protected]"
    [core]
        sshCommand = "ssh -i ~/.ssh/id_rsa_myuser_at_domain.pub"

In theory, this tells git that, whenever making commits inside the directory ~/git/my_professional_project/ to push commits via SSH with the key ~/.ssh/id_rsa_myuser_at_domain.pub.

And I found this did indeed allow git to commit to my professional account. However, despite the "IncludeIf" statement, I found the side-effect of this was that it also made git use my professional key for all git commits, resulting in the notorious error:

You are not allowed to push code to this project.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

Is there a mistake in my includeIf rule syntax? Why does this configuration force git to use the wrong SSH key?


Solution

Your includeIf syntax is indeed incorrect. What you've written is an includeIf section with no configuration settings, then a user section with an email setting, and then a core section with an sshCommand setting, albeit with some odd indenting.

If you want to use an includeIf section, you need to place the additional options in a separate file, and include that:

[includeIf "gitdir:~/git/my_professional_project/"]
    path = ~/.config/git/professional


Answered By - bk2204