Connect to Github using SSH keys

By xngo on May 18, 2020

Everytime that I use Git to access my repositories, it asks for my username and password. I do a lot pushes, pulls and commits. This has become really annoying. The best way that I found to avoid entering my username and password is to connect to Gitlab using a SSH key. Here are the steps that I did.

Create SSH key

To create SSH key, run the following command.

ssh-keygen -t rsa -C "your_email@example.com" -b 4096

Follow the instructions and enter a passphrase. After you are done, your public key is saved in ~/.ssh/id_rsa.pub. Open that file and copy its content. You will need to paste it in Gitlab.

SSH key-gen example

Add SSH key in Gitlab

  1. From Gitlab.com, navigate to your profile Settings > SSH keys.
    Gitlab - Add SSH key
  2. Add the SSH key by pasting the content of ~/.ssh/id_rsa.pub file.

Tell Git which private key to use

If ~/.ssh/config doesn't exist, then create it. Then, add the followings:

host gitlab.com
 HostName gitlab.com
 IdentityFile ~/.ssh/id_rsa.pub
 User git

Test

Try git clone or git pull origin master.

git clone https://gitlab.com/some-user/example.git
git pull origin master

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.