GitLab Container Registry for CI/CD and Seamless Deployment

Photo by CHUTTERSNAP on Unsplash

GitLab Container Registry for CI/CD and Seamless Deployment

GitLab is an excellent SaaS tool for storing your code and automating workflows. If you have a managed Kubernetes cluster, you can also use GitLab as the container registry and the CI/CD platform.

Create Secret

First, you need to create a permanent Access Token from your GitLab repository or group that will have access to all the child repositories and the container registry. This token will be used by kubelet to pull images from the GitLab-managed container registry. The secret creation will look like the following.

kubectl create secret docker-registry gitlab-token-auth \
   --docker-server=https://registry.gitlab.com \
   --docker-username=kubelet \
   --docker-password=1234zxcv0987

CI/CD Pipeline

If you trigger a GitLab workflow inside GitLab-hosted runners, the workflow will have the privilege to push container images into the same code repository. Built-in variables like CI_REGISTRY_USER, CI_REGISTRY_PASSWORD, and CI_REGISTRY_IMAGE will be automatically populated during the pipeline run. Here is the code snippet that needs to be added to push the newly built image into Gitlab's container registry.

push:
  image: docker:24
  services:
    - docker:24-dind
  stage: push
  script:
    - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
    - docker build . -t $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA
    - docker push $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA

Deployment

Once the image is pushed into Gitlab registry, you can use the previosly created Secret to pull the image into Kubernetes and run it. You will need to patch your deployment to include the imagePullSecrets.

spec:
  metadata:
    spec:
      containers:
      - name: app
        image: $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA
      imagePullSecrets:
      - name: gitlab-token-auth