Search code examples
gitgogetpackagegitlab

How to use Go with a private GitLab repo


GitLab is a free, open-source way to host private .git repositories but it does not seem to work with Go. When you create a project it generates a URL of the form:

[email protected]:private-developers/project.git

where:

  • 1.2.3.4 is the IP address of the gitlab server
  • private-developers is a user group which has access to the private repo

Golang 1.2.1 doesn't seem to understand this syntax.

go get [email protected]:private-developers/project.git

results in:

package [email protected]/project.git: unrecognized import path "[email protected]/project.git"

Is there a way to get this to work?


Solution

  • This issue is now resolved in Gitlab 8.* but is still unintuitive. The most difficult challenge indeed is go get and the following steps will allow you to overcome those:

    1. Create an SSH key pair. Be sure to not overwrite an existing pair that is by default saved in ~/.ssh/.

      ssh-keygen -t rsa -b 4096
      
    2. Create a new Secret Variable in your Gitlab project. Use SSH_PRIVATE_KEY as Key and the content of your private key as Value.

    3. Modify your .gitlab-ci.yml with a before_script.

      before_script:
        # install ssh-agent if not already installed
        - 'which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )'
        # run ssh-agent
        - eval $(ssh-agent -s)
        # add the SSH key stored in SSH_PRIVATE_KEY
        - ssh-add <(echo "$SSH_PRIVATE_KEY")
        # for Docker builds disable host key checking
        - mkdir -p ~/.ssh
        - '[[ -f /.dockerenv ]] && echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config'
      
    4. Add the public key from the key pair created in step 1 as a Deploy Key in the project that you need to go get.