Tell Git which SSH key to use

Submitted by Peter Majmesku on Mon, 05/21/2018 - 13:24

I am using Bitbucket as a cloud provider for Git VCS hosting. I could not push to Bitbucket. I have multiple accounts on Bitbucket, so the issue could have to do with that. So I was going to configure my projects Git config to distinct between several private SSH keys for 1 host. A thread on Stackoverflow was helpful, to learn how to tell Git which SSH key it has to use for a specific remote. Because my access has been refused with the following error:

repository access denied.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

Firstly I had to set the host in my ~/.ssh/config file:

Host bitbucket_privat
  User peter_majmesku
  IdentityFile ~/.ssh/bitbucket_privat  

Then I've needed to edit the PROJECT_DIRECTORY/.git/config file in my project to assign the SSH config:

[remote "origin"] 
  url = bitbucket_privat:peter_majmesku/permissions_by_term.git 
  fetch = +refs/heads/*:refs/remotes/origin/*

Finished! Afterwards I was finally able to push to Bitbucket:

peter@NB8 permissions_by_term (8.x-1.x) $ git push
Counting objects: 1617, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (847/847), done.
Writing objects: 100% (1617/1617), 1.83 MiB | 5.73 MiB/s, done.
Total 1617 (delta 923), reused 1225 (delta 696)
remote: Resolving deltas: 100% (923/923), done.
To bitbucket_privat:peter_majmesku/permissions_by_term.git
* [new branch] 8.x-1.x -> 8.x-1.x

In doubt you can clear all ssh keys and add one seperately: 

ssh-add -D

Add key:

ssh-add ~/.ssh/bitbucket_privat

Check which key is used:

ssh -v