Reputation: 64880
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?
Upvotes: 3
Views: 1833
Reputation: 489858
The includeIf
directive / section uses only one field, named path
:
[includeIf "expression"]
path = /path/to/file
You cannot add core
and user
sections in this file. You must put the [core]
and [user]
directives in another configuration file. You then use the includeIf
directive (your existing condition is fine) with path
to tell Git where to find the other file.
Upvotes: 2
Reputation: 76964
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
Upvotes: 3