4

I would like to use a specific SSH key when using Git through PyCharm on Windows.

Things I have tried:

What else can I do?

1 Answer 1

5

Apparantly JetBrains IDEs (like PyCharm) use the Windows commandline to interact with git.
See here

So the first step is to startup the Windows Command Prompt and check if you can use Git with a specific SSH key that way.
In my case this was not possible, even though I had configured the config file located at ~/.ssh/config (when accessed through Git Windows) or C:\Users\<Me>\.ssh\config.
This is why the SO posts mentioned in my question did not solve my problem.

The second step is to figure out which config file instead is used by Git when accessed through the Windows Command Prompt.
This provided me the clue that Git on Windows can use an internal ssh config file called ssh_config (instead of config) and located near the git.exe (instead of in a subdir of your homedir).
I found Git's location using where git which indicated C:\Program Files\Git-2.16.1\cmd\git.exe.
So the config I was looking for was located at C:\Program Files\Git-2.16.1\etc\ssh\ssh_config.

The third step is adjusting that ssh_config file similar to the config file.
For me this looked like this:

Host <some-name>
        HostName gitlab.com
        IdentityFile C:\Users\<Me>\.ssh\<my-non-default-key>
        # Prevents usage of the default IdentityFile
        # See: https://stackoverflow.com/a/11251797
        IdentitiesOnly yes
        # Prevents warning when pulling from Gitlab.
        # See: https://stackoverflow.com/a/67556915
        UpdateHostKeys no

The fourth and last step is to change the remote in the Git repository such that it uses the name <some-name> specified in the ssh_config file.
Get the original remote first using git remote -v.
This gives something like this:
[email protected]:some/subdirs/to/the/repository.git
Now swap out the gitlab.com part for <some-name> specified in the ssh_config file, like this:
git remote set-url origin git@<some-name>:some/subdirs/to/the/repository.git

Summary:

  • When using a JetBrains IDE like PyCharm it uses Git over the Windows Command Prompt
  • Find out the location of Git in the Windows Command Prompt
  • Adjust the ssh_config file located at this Git location
  • Set the remote url of the repository such that it uses the host name specified in the ssh_config file
1
  • The correct User field in ssh_config for most GitHub/GitLab installations I've seen is 'git' and NOT your web login to GH/GL. By default it uses your Operating System's username, which is not what you want.
    – Marcin
    Commented May 25, 2023 at 18:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.