Using SSH to push commit to GitLab

雖然網路上教學都推薦使用 GitHub 搭配 Hexo 和 Netlify 來架 blog, 但身為一個不合時宜的邊緣人, 當然要先試 Netlify CLI 直接上傳, 大概用了近半年, 每次更新常常相依模組大爆炸, 除錯的時間都可以打好幾場魔物, 上傳速度又慢, 就退而求其次, 試試 GitLab 看看

不試還好, 用了才發現 GitLab 說明文件寫得有點糟, 搞了半天才搞定 SSH push, 紀錄一下處理過程

依 GitLab 網頁說明建立 Repo

1
2
3
4
5
git init --initial-branch=main
git add .
## 其實這邊如果把 add orgin 改成 git@gitlab.com:MY_REPO_NAME/blog.git 就可以省掉最後一個步驟
git remote add origin https://gitlab.com/MY_REPO_NAME/blog.git
git commit -m "Hexo Blog init"

在 GitLab 網站個人帳號設定新增 key

1
2
3
4
5
6
7
8
9
10
11
12
13
## 將 pub key 複製到 GitLab 內的個人設定
## https://docs.gitlab.com/ee/user/ssh.html#add-an-ssh-key-to-your-gitlab-account

cat ~/.ssh/id_ed25519.pub
...
## 複製貼上到 GitLab 帳號設定內

## 如果有多把 key 的話, 可以在 ~/.ssh/config 內指定對應的 key

Host gitlab.com
HostName gitlab.com
IdentityFile ~/.ssh/id_ed25519

測試 SSH 連線

1
2
3
4
5
6
7
8
9
10
11
/MY_BLOG_PATH/blog/public (main ✔) ᐅ ssh -T git@gitlab.com
The authenticity of host 'gitlab.com (172.65.251.78)' can't be established.
ED25519 key fingerprint is SHA256:eUXGGm1YGsMAS7vkcx6JOJdOGHPem5gQp4taiCfCLB8.
This key is not known by any other names.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added 'gitlab.com' (ED25519) to the list of known hosts.
git@gitlab.com: Permission denied (publickey).
## 錯誤是因為我有多把 ED25519 的 KEY, 照上面設定對應 KEY 後就可以成功連線
/MY_BLOG_PATH/blog/public (main ✔) ᐅ ssh -T git@gitlab.com
Welcome to GitLab, @ACCOUNT_NAME!

設定 git remote

push 的時候要求輸入帳號密碼, 代表尚未設定完成, 還差最後一步
先用 git remote -v 檢查目前設定
如果看到是 https://gitlab.com/, 再利用 git remote set-url origin 改成 git@gitlab.com:…
應該就大功告成

1
2
3
4
5
6
7
8
9
/MY_BLOG_PATH/blog/public (main ✔) ᐅ git remote -v
origin https://gitlab.com/MY_REPO_NAME/blog.git (fetch)
origin https://gitlab.com/MY_REPO_NAME/blog.git (push)
/MY_BLOG_PATH/blog/public (main ✔) ᐅ git remote set-url origin
git@gitlab.com:MY_REPO_NAME/blog.git
/MY_BLOG_PATH/blog/public (main ✔) ᐅ git remote -v
origin git@gitlab.com:MY_REPO_NAME/blog.git (fetch)
origin git@gitlab.com:MY_REPO_NAME/blog.git (push)