如何將 SSH Key 新增到 GitLab 中?

极狐GitLab發表於2024-09-05

本文分享如何生成 SSH Key 並新增到極狐GitLab 中,然後用 SSH Key 進行程式碼拉取。

極狐GitLab 是 GitLab 在中國的發行版,可以一鍵私有化部署,對於中國開發者更友好。詳細安裝步驟可以檢視官網 https://dl.gitlab.cn/qrrj8903

SSH Key 對於透過 ssh 來進行極狐GitLab 程式碼拉取是重要的,完成整個流程一般分為三步:

  • SSH Key 的生成
  • 新增 SSH Key 到極狐GitLab 中
  • 使用 ssh 克隆程式碼

第一步:生成 SSH Key

使用 ssh-keygen命令來生成 SSH Key:

ssh-keygen -t rsa -C "jh-gitlab@devops.com"
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): /root/.ssh/id_rsa_jh_gitlab
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa_jh_gitlab
Your public key has been saved in /root/.ssh/id_rsa_jh_gitlab.pub
The key fingerprint is:
SHA256:OuX13mP/EASg/KljuZXrWsq65WIvzFaU9T72tXisVPc jh-gitlab@devops.com
The key's randomart image is:
+---[RSA 3072]----+
|          ...    |
|       . ..  .   |
|        oo .  .  |
|        o. ...   |
|       .S +.  ...|
|       +.+ o+ ..+|
|     oo.B +..++.E|
|      B* * o.o+= |
|     oo*Boo .o+o+|
+----[SHA256]-----+

生成之後,可以在 ~/.ssh目錄下面檢視:

ls -ltr ~/.ssh/
total 24
-rw------- 1 root root  676 Apr  3 14:49 authorized_keys
-rw-r--r-- 1 root root  284 Sep  5 14:15 known_hosts
-rw-r--r-- 1 root root  574 Sep  5 14:16 id_rsa_jh_gitlab.pub
-rw------- 1 root root 2610 Sep  5 14:16 id_rsa_jh_gitlab

可以看到最下面兩個是剛才生成的 SSH Key pair。pub 是公鑰,另外一個是私鑰。可以用 cat命令檢視兩個 key 的內容。

第二步:將 SSH Key 新增到極狐GitLab

點選左上角的頭像 --> 偏好設定 --> SSH 金鑰

file

點選右上角的新增新金鑰:

file

將第一步中生成的 pub 內容複製到金鑰方框中,然後可以自定義標題,選擇到期時間,直接點選新增金鑰即可完成 SSH Key 的新增。

第三步:clone 倉庫程式碼

新增完 SSH Key 就可以使用 ssh 來 clone 程式碼了:

git clone git@jhma.jihulab.net:root/kubernetes-agent.git
Cloning into 'kubernetes-agent'...
remote: Enumerating objects: 21, done.
remote: Total 21 (delta 0), reused 0 (delta 0), pack-reused 21 (from 1)
Receiving objects: 100% (21/21), 4.09 KiB | 838.00 KiB/s, done.
Resolving deltas: 100% (2/2), done.

相關文章