Skip to content

Instantly share code, notes, and snippets.

@moisoto
Created November 16, 2023 17:44
Show Gist options
  • Save moisoto/6f67cd7357ea1de4f685538a3e7b6645 to your computer and use it in GitHub Desktop.
Save moisoto/6f67cd7357ea1de4f685538a3e7b6645 to your computer and use it in GitHub Desktop.
GIT - Working with Private Repositories

Working with Private Repositories

Using SSH Authorization Key on Github

The first step will be to add your public key to github:

  • Go to Settings -> SSH and GPG Keys (currently https://github.com/settings/keys).
  • Create a SSH Authentication Key, you can use your current id_rsa public key (you should have the private key loaded on ~/.ssh/id_rsa).
  • You can clone your private repository by using the git clone command like this:
git clone git@github.com/your_user/some_private_repo.git

Using several github accounts.

Github will only let you assign a given SSH Authorization Key on a single account. So you can't load your id_rsa public key on other github accounts. However there is a workaround by using the ssh config file on ~/.ssh/config.

Create a Keypair for the given github accound:

Run the following command to create a new keypair. When asked, specify a name for use with your files, like othergithub_rsa

ssh-keygen -t rsa -b 4096 -C "some_mail@some_website.com"

Add the public key (located on ~/.ssh/othergithub_rsa.pub) on the other github account as an Authorization SSH Key.

Adding a entries to your ssh config file:

Now add an entry to your ~/.ssh/config file:

Host other.github.com
    Hostname github.com
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/othergithub_rsa

Notice two things:

  • You specified a hostname as other.github.com
  • You specified the filename you just created on the IdentityFile entry

Now you can trick the git clone command to use that specific private key by using the host alias of the config instead of github.com:

git clone git@other.github.com/other_user/other_private_repo.git

Defaulting to SSH:

It may be useful to also set your ~/.gitconfig file to use ssh as default for specific urls.

For example:

[url "ssh://git@github.com/"]
        insteadOf = https://github.com/

Note: This is useful for example when importing private Go Modules. You can even be more specific, like this:

[url "ssh://git@github.com/"]
        insteadOf = https://github.com/your_user/private_library
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment