git

How to configure a local Git repository to use a specific SSH key

web3coach

Lukas Lukac

Posted on June 12, 2020

How to configure a local Git repository to use a specific SSH key

Sounds familiar?

git push origin master

fatal: Could not read from remote repository.
Please make sure you have the correct access rights
Enter fullscreen mode Exit fullscreen mode

When you work on multiple projects from the same machine, you often need to use a different SSH key per repository.

For example you may have two repositories:

  • github.com/work/work-repo-1 [work SSH key]
  • github.com/personal/personal-repo-1 [personal SSH key]

If you don't want to mess around with the global SSH config stored by default in ~/.ssh/config, you can configure the local one, located as a hidden folder inside your cloned repository path.

Open the local repository's git config file:

cd $HOME/your-projects/github.com/work/work-repo-1
vim .git/config
Enter fullscreen mode Exit fullscreen mode

You will see settings like:

[core]
        repositoryformatversion = 0
        filemode = true
        bare = false
        logallrefupdates = true
        ignorecase = true
        precomposeunicode = true

[remote "origin"]
        url = git@github.com:web3coach/web.git
        fetch = +refs/heads/*:refs/remotes/origin/*
Enter fullscreen mode Exit fullscreen mode

Individualize the settings

 Configure your user

Configure your user's name, email by modifying the user group settings. This is important because this name and email will appear in your project's git commit history.

[user]
        name = Lukas Lukac
        email = lukas@web3.coach
Enter fullscreen mode Exit fullscreen mode

 Configure your auth permissions

Git uses SSH for permissions authentication. Specify what SSH key you want to use by defining the sshCommand setting inside the core group:

[core]
        sshCommand = "ssh -i ~/.ssh/id_rsa_web3coach"
Enter fullscreen mode Exit fullscreen mode

All together:

[user]
        name = Lukas Lukac
        email = lukas@web3.coach

[core]
        repositoryformatversion = 0
        filemode = true
        bare = false
        logallrefupdates = true
        ignorecase = true
        precomposeunicode = true

        sshCommand = "ssh -i ~/.ssh/id_rsa_web3coach"

[remote "origin"]
        url = git@github.com:web3coach/web.git
        fetch = +refs/heads/*:refs/remotes/origin/*
Enter fullscreen mode Exit fullscreen mode

Alternative

Prefix your git command with an ENV variable on the fly:

GIT_SSH_COMMAND='ssh -i ~/.ssh/id_rsa_web3coach' git push origin master
Enter fullscreen mode Exit fullscreen mode

Thank you for reading.


If you like this tutorial, follow me on Twitter where I share my blockchain programming journey: https://twitter.com/Web3Coach

💖 💪 🙅 🚩
web3coach
Lukas Lukac

Posted on June 12, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related