gitlab Setup Gitlab CI to allow cloning other private repositories


Example

Some projects like GoLang might need to clone other dependent GitLab repositories during build. To get this working you can add a Deploy Key to dependent repositories and put the private key (without password) into the origin repository.

Create and check-in a SSH key inside the Git Repository that depends on some other repository during build time:

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

Use the deploykey.pub to configure a deploykey in the dependent repository. You can find an Deploykey page in the GitLab Project Settings.

Now add the following to you .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

Now any call to git clone inside your build should work. Even if it's via some other tools like go get, govendor sync, or whatever you are using.