gitlab CI使用bitbucket submodule

如何集成SSH到gitlab CI

Posted by Swifty Wang on December 14, 2018

事件描述

最近一个新的项目开在了gitlab.然而里面的submodule依然依赖bitbucket一个private repository,导致gitlab没有权限拿到bitbucket的repository。

解决方法

先使用ssh-keygen本地生成private keypublic key

ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/swiftywang/.ssh/id_rsa): gitlab
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in gitlab.
Your public key has been saved in gitlab.pub.

注意此处Enter file in which to save the key不能直接回车不然会覆盖本机当前的ssh key。
将生成的gitlab.pub上传至bitbucket project或group的SSH key中。
将生成的gitlab上传至gitlab->project->settings->CI/CD->variable中 并勾上protected 防止泄露private key。
在项目中.gitlab-ci.yml- git submodule sync --recursive拿submodule前,先去获取ssh private key并存入ssh-agent,方法如下

before-script:
  - eval $(ssh-agent -s)
  - mkdir ~/.ssh/
  - '[[ -f /.dockerenv ]] && echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config'
  - ssh-add <(echo "$GITLAB_SSH_KEY")

  - git submodule sync --recursive
  - git submodule update --init --recursive
  ...

至此gitlab CI就可以从bitbucket获取private repository