Skip to content

Instantly share code, notes, and snippets.

@JensForstmann
Last active April 29, 2022 17:12
Show Gist options
  • Save JensForstmann/47a2d5b62644001a16443e16ffd1f549 to your computer and use it in GitHub Desktop.
Save JensForstmann/47a2d5b62644001a16443e16ffd1f549 to your computer and use it in GitHub Desktop.
Use specific SSH key with Git

Sometimes you want to use a specific SSH key when accessing a Git repository, e.g. when using a deploy key.

Method 1 - Overwrite Git's SSH command

Use a key for every following git command:

export GIT_SSH_COMMAND="ssh -i /path/to/id_rsa"

Methodd 2 - Use different keys for different repositories

Use different keys for different repositories:

Source: https://docs.github.com/en/developers/overview/managing-deploy-keys#using-multiple-repositories-on-one-server

In short:

  • Add a new entry in ~/.ssh/config for every repository using a "fake" hostname.
  • Use the "fake" hostname when cloning.

Example ~/.ssh/config:

Host github.com-repo-0
     Hostname github.com
     IdentityFile=/home/user/.ssh/repo-0_deploy_key

Host github.com-repo-1
     Hostname github.com
     IdentityFile=/home/user/.ssh/repo-1_deploy_key

Example command:

git clone git@github.com-repo-1:OWNER/repo-1.git
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment