Search code examples
dockergitlabgitlab-cidocker-registrygitlab-ci-runner

GitLab CI ssh registry login


I have a GitLab project gitlab.com/my-group/my-project which has a CI pipeline that builds an image and pushes it to the project's GitLab registry registry.gitlab.com/my-group/my-project:tag. I want to deploy this image to Google Compute Engine, where I have a VM running docker.

Easy enough to do it manually by ssh'ing into the VM, then docker login registry.gitlab.com and docker run ... registry.gitlab.com/my-group/my-project:tag. Except the docker login command is interactive, which is a no-go for CI. It can accept a username and password on the command line, but that hardly feels like the right thing to do, even if my login info is in a secret variable (storing my GitLab login credentials in a GitLab secret variable?...)

This is the intended workflow on the Deploy stage of the pipeline:

  1. Either install the gcloud tool or use an image with it preinstalled
  2. gcloud compute ssh my-gce-vm-name --quiet --command \ "docker login registry.gitlab.com && docker run registry.gitlab.com/my-group/my-project:tag"

Since the gcloud command would be running within the GitLab CI Runner, it could have access to secret variables, but is that really the best way to log in to the GitLab Registry over ssh from GitLab?


Solution

  • I'll answer my own question in case anyone else stumbles upon it. GitLab creates ephemeral access tokens for each build of the pipeline that give the user gitlab-ci-token access to the GitLab Registry. The solution was to log in as the gitlab-ci-token user in the build.

    .gitlab-ci.yml (excerpt):

    deploy:
      stage: deploy
      before_script:
        - gcloud compute ssh my-instance-name --command "docker login registry.gitlab.com/my-group/my-project -u gitlab-ci-token -p $CI_BUILD_TOKEN"