Search code examples
gitssh-keys

Specify key file in a specific git repository


I am using a collaborative user, so it is not possible to change global folder. I have a git repository connected with several remotes. I need to access different remotes with different rsa key. Is it possible to insert the key path within native git, e.g. maybe inside .git/config, so I don't need to repeat entering the key path when i am doing clones,fetches,pushes,pulls?

Edit: I am aware of similar questions, for example Specific RSA keys per git repo, but it does not provide an exact answer to "per repo".


Solution

  • You need to replace the ssh url of your submodules by ssh url using ~/.ssh/config entry names (with ~ refering the $HOME of the global user)

    Your ~/.ssh/config will include the path of the relevant private keys:

    Host repo1
      HostName git.myhost.lan
      User git
      IdentityFile /path/to/global/user/.ssh/repo1PrivateKey
    

    And for the submodule repo1:

    git config --file=.gitmodules submodule.repo1 .url repo1:user/repo1
    # if needed to follow a branch (if not, skip it)
    git config --file=.gitmodules submodule.repo1 .branch abranch
    git submodule sync
    git submodule update --init --recursive --remote
    git add .
    git commit -m "Change submodule repo1 url"
    git push
    

    Note: git config + git submodule sync can be replaced.
    See "Git submodule url changed" and the new command (Git 2.25, Q1 2020)

    git submodule set-url [--] <path> <newurl>