設定 Gitlab CI 以允許克隆其他私有儲存庫

像 GoLang 這樣的一些專案可能需要在構建期間克隆其他依賴的 GitLab 儲存庫。要使此工作正常,你可以向相關儲存庫新增部署金鑰,並將私鑰(無密碼)放入源儲存庫。

在構建期間依賴於其他儲存庫的 Git 儲存庫中建立並簽入 SSH 金鑰:

ssh-keygen -t rsa -b 4096 -C "My CI Deploykey"

# In the following promt name the key "deploykey" and leave the passphrase empty
Generating public/private rsa key pair.
Enter file in which to save the key (/home/user/.ssh/id_rsa): deploykey
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in deploykey.
Your public key has been saved in deploykey.pub.

# check-in both files

使用 deploykey.pub 在依賴儲存庫中配置 deploykey。你可以在 GitLab 專案設定中找到 Deploykey 頁面。

現在將以下內容新增到 .gitlab-ci.yml

before_script:
  # Git and SSH setup to clone private repos
  # Needs the deploykey file to be installed in all dependent repositories
  - git config --global url."git@gitlab.com:".insteadOf "https://gitlab.com/"
  # Add gitlab to known_hosts
  - mkdir -p ~/.ssh && chmod 700 ~/.ssh
  - ssh-keyscan -H gitlab.com >> ~/.ssh/known_hosts
  # Start the ssh agent and add the deploykey
  - chmod 400 deploykey
  - eval $(ssh-agent -s)
  - ssh-add deploykey

現在,在你的構建中任何對 git clone 的呼叫都應該有效。即使它是通過其他工具,如 go getgovendor sync,或任何你正在使用的工具。