Search code examples
windowsgitpycharmjetbrains-idessh-keys

How to automatically use a specific SSH key when using Git through a JetBrains IDE (i.e. PyCharm) on Windows?


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?


Solution

  • 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:
    git@gitlab.com: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