How To Set Up GitLab SSH Key on macOS

Prerequisite

  • GitLab account
  • macOS

If you want to clone a repository from GitLab, there are 2 ways to do it.

The first choice is using HTTPS, but you need to insert your GitLab username and password every time you clone a repository.

The second choice is using SSH key. By using SSH key, you can clone a repository from GitLab without inserting username and password. Because, SSH key will handle the authentication.

Today, we will learn how to set GitLab SSH Key on macOS.

Generate SSH Key

  • Open your terminal, go to .ssh directory
cd ~/.ssh
  • Create your SSH Key. We will use RSA SSH key configuration.
ssh-keygen -t rsa -C "your_email_address"
  • You'll see a message to insert file name for SSH key. For example, I insert: id_rsa_gitlab_key
Generating public/private rsa key pair.
Enter file in which to save the key (/home/user/.ssh/id_rsa):
  • Next, you'll be asked to enter passphrase. Just leave it empty
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
  • Congratulations, you just create your own SSH Key. To check SSH key exist or not, run:
ls -al
  • You will find two files:
id_rsa_gitlab_key // private key
id_rsa_gitlab_key.pub // public key

Register SSH Key

To make sure your mac able to authenticate automatically with GitLab, you need to register your SSH key to SSH agent in your mac.

  • Start the ssh-agent.
eval $(ssh-agent -s)
  • Add your SSH key to SSH agent.
ssh-add -K ~/.ssh/id_rsa_gitlab_key
  • Open SSH config file.
nano ~/.ssh/config
  • To make sure your SSH key added automatically to SSH agent after a reboot (or logout/login), we need to set config file.
Host gitlab.com
   AddKeysToAgent yes
   UseKeychain yes   
   // IdentityFile is your ssh key file location
   IdentityFile ~/.ssh/id_rsa_gitlab_key
  • Save config file by using ctrl + x.

  • Check your SSH key in SSH agent.

ssh-add -l
  • You will see your SSH key has been registered to SSH agent.

Insert SSH Key to GitLab Account

  • Copy your SSH Key. This key will be copied to your GitLab account.
pbcopy < ~/.ssh/id_rsa_gitlab_key.pub
  • Go to gitlab.com, then go Profile >> SSH Keys menu (https://gitlab.com/profile/keys).

Screen Shot 2020-11-08 at 13.55.09.png

  • Paste your SSH Key to Key input, and also add the Title.

  • Press Add Key button.

  • To test whether your SSH key was added correctly, run:

ssh -T git@gitlab.com
  • It should return:
Welcome to GitLab, @your_gitlab_username!

Great, now you can clone and push a repository in GitLab, getting work done and have a time with your family 😁 .

Source

No Comments Yet