Git 託管平台綁定不同的 SSH key

Kion
3 min readApr 9, 2020

--

https://medium.com/%E8%83%A1%E8%A8%80%E4%BA%82%E8%AA%9E/generating-a-new-ssh-key-4f7b03a7b186

目次

1. 產生 SSH key
2. 宣告 SSH key 所屬 Host

Git 託管平臺有很多種,像是:GitHub、Gitlab、Bitbucket….等等
當我們想讓不同的平台綁定不同的 SSH key
就不是像以往一樣,只需產生 SSH key 再將其貼上而已

那我們就以 GitLab 為例開始吧!

產生 SSH key

第一步,也是最重要的一步
先產生 SSH key

打開 terminal 輸入:

ssh-keygen -t rsa -b 4096 -C "email@example.com(我的信箱)"

但請記得要改一下檔名,假設叫 example,就在

Enter file in which to save the key:

輸入 example 當作檔名

ls 看一下,果然多了:

example example.pub

.pub 的是公鑰,可以給出去的

另一個是私鑰,是不行給出去的

宣告 SSH key 所屬 host

在程序上我們只需 cat 公鑰,貼到 GitLab 即可
不知道流程可以參考 這篇文章

但正因為我們沒有在我們內部的設定檔,宣告哪隻 key 適用於哪個託管平台
當我們想透過 SSH 的方式 clone 專案時,會導致使用 SSH 連線失敗,專案 clone 不下來

我們切至 .ssh 的目錄

cd ~/.ssh

新增名為 config 的檔案

touch config

接著,開始編輯 config

vim config

根據 Gitlab 官方文件,依照使用的方案,所設定的 Host 不同:

# GitLab.com // 雲端版本Host gitlab.com
Preferredauthentications publickey
IdentityFile ~/.ssh/gitlab_com_rsa
# Private GitLab instance // 私人架設Host gitlab.company.com
Preferredauthentications publickey
IdentityFile ~/.ssh/example_com_rsa

Host

透過 Host 來檢查要套用哪些設定

如果是連線至 gitlab.com 就是對應 gitlab_com_rsa
如果是連線至 gitlab.company.com 就是對應 example_com_rsa

這樣就完成設定啦!

拍個手讓我知道,這個文章對你們有幫助 ♥(´∀` )人

參考資料

  1. Working with non-default SSH key pair paths

--

--

Kion
Kion

Written by Kion

程式就是利用自動化與排程的特性解決問題 文章分類總覽: https://hackmd.io/@Kion/SyvyEks0L

No responses yet