/ Dev

How to use more than one SSH key

There are several ways to use a different SSH key when pulling from Git:

1. Using the -i flag:

  • Specify the desired key file directly in the Git command:

    git pull -i /path/to/your/key
    

2. Setting the GIT_SSH_COMMAND environment variable:

  • Use this for a more permanent solution within the current terminal session:

    export GIT_SSH_COMMAND="ssh -i /path/to/your/key"
    git pull
    

3. Configuring the SSH config file (~/.ssh/config):

  • Create aliases for different SSH hosts and keys:

    Host work
       Hostname github.com
       IdentityFile ~/.ssh/work_key
    
    Host personal
       Hostname github.com
       IdentityFile ~/.ssh/personal_key
    
  • Use the alias in Git commands:

    git pull work:username/repo.git
    

4. Configuring Git's core.sshCommand:

  • Customize SSH commands for specific repositories:

    git config core.sshCommand "ssh -i /path/to/your/key"
    git pull
    

Key points to remember:

  • Key generation: If you don't have a separate key, generate one using ssh-keygen.
  • Public key addition: Add the public key to your Git service account (e.g., GitHub, GitLab).
  • Multiple keys: Manage multiple keys effectively using the SSH config file for organization.
  • Preferred method: Choose the method that best suits your workflow and preferences.

Additional tips:

  • Use the ssh-add command to load keys into the SSH agent for easier management.
  • Consider using a password manager to securely store SSH key passphrases.