Skip to content

Switching SSH Keys Between Git Projects

Git/ (Posted on )

I have been working on some projects from two different GitHub accounts. Each account has its own SSH key attached to it, therefore I must swap between two SSH keys whenever working on projects owned by the corresponding account.

Instead of changing the default SSH key whenever working on another project, you can configure Git to use a specific key per project.

For the following solution to work, you must have at least Git version 2.10.0 installed.

Verify that by running the following command in your terminal.

git --version

If your Git version allows it, run the following command in terminal from your project repository.

git config --add core.sshCommand "ssh -o IdentitiesOnly=yes -i ~/.ssh/path-to-your-key -F /dev/null"

Or you can do it manually by opening .git/config file inside of your repository.

nano .git/config

And setting the sshCommand variable to specify the SSH identity file that the ssh command will use when working with the current Git repository.

[core]
        sshCommand = ssh -o IdentitiesOnly=yes -i ~/.ssh/path-to-your-key -F /dev/null

The sshCommand variable specifies how Git uses the ssh CLI command to interact with the repository. The configuration changes the identity file, specified in -i flag, that will be used to pull and push changes to this project. The -F /dev/null argument ignores SSH configuration file, if one exists in ./ssh/config. The -o IdentitiesOnly=yes option ensures that only the specified key in -i flag is used. Otherwise, ssh-agent might try a different key first and fail.

Setting Up A Generic Solution

There is also a solution to avoid configuring every project individually. I’ve written a post about creating multiple Git configurations.

In short, every project that must use a different SSH key should be located under a common directory. The global .gitconfig must include the following configuration that specifies that a different configuration file will be used for the projects under this common directory.

[includeIf "gitdir:~/path/to/projects-that-use-different-key/"]
        path = ~/path/to/projects-that-use-different-key/.gitconfig

After that, just create a .gitconfig file inside the common ~/path/to/projects-that-use-different-key/ directory and specify the sshCommand to be used in every project under this directory.

[core]
        sshCommand = ssh -o IdentitiesOnly=yes -i ~/.ssh/path-to-your-key -F /dev/null

References