How to use Go with a private GitLab repo

GitLab version 11.8+ and Go version 1.13+ will work with BASIC auth by using your GitLab personal token. Go to Settings -> Access Tokens in your Gitlab, add a personal access token or use your existing one. In your ~/.netrc file, add following lines:

machine <your GitLab domain> (e.g. gitlab.com)
login <your GitLab id>
password <your GitLab personal access token>

Then you should be able to do go get locally.

If you need to build it in CI, then add following line in your .gitlab-ci.yml file:

before_script:
    - echo -e "machine <your GitLab domain>\nlogin gitlab-ci-token\npassword ${CI_JOB_TOKEN}" > ~/.netrc

Easiest way with Gitlab

before_script:
  - git config --global url."https://gitlab-ci-token:${CI_JOB_TOKEN}@gitlab.com/".insteadOf https://gitlab.com/
  - go env -w GOPRIVATE=gitlab.com/${CI_PROJECT_NAMESPACE}

See more details here: https://docs.gitlab.com/ee/user/project/new_ci_build_permissions_model.html#dependent-repositories


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.


Run this command:

git config --global url."[email protected]:".insteadOf "https://1.2.3.4/"

Assuming you have the correct privileges to git clone the repository, this will make go get work for all repos on server 1.2.3.4.

I tested this with go version 1.6.2, 1.8, and 1.9.1.