Deploying applications to Kubernetes using GitLab CI/CD can greatly streamline your DevOps workflow. While GitLab offers integration with Kubernetes cluster by installing a GitLab agent, there are situations where installing a GitLab agent on your Kubernetes cluster is not feasible. This guide will show you how to set up a GitLab CI/CD pipeline to deploy an application to Kubernetes using both kubectl and Helm without installing the GitLab agent. Let’s dive in!

KUBECONFIG

First, you need to configure the KUBECONFIG variable with the content of your kubeconfig file that has sufficient permissions.

  1. In your GitLab project, navigate to Settings > CI / CD > Variables.
  2. Click Add variable.
  3. Set the variable Type to File.
  4. Set the Key to KUBECONFIG (this is a Kubernetes convention).
  5. Paste the content of your kubeconfig file into the Value field.
  6. Click Add variable.

GitLab will make the KUBECONFIG file available to your jobs, and the value of KUBECONFIG will be set to the path where the file is placed. There’s no need to manually specify the path for KUBECONFIG since GitLab handles it automatically.

⚠️
The KUBECONFIG variable will not be hidden in GitLab because the file content doesn't meet the masking criteria. Be careful when using cat or any commands that display the KUBECONFIG variable in your script, as it might expose sensitive information.

.gitlab-ci.yml

Here’s an example pipeline using bitnami/kubectl for kubectl commands and alpine/helm for helm commands, providing convenience for deploying applications to Kubernetes.

kubectl:
  image: bitnami/kubectl:latest
  script:
    - kubectl cluster-info
    - echo "Now you can use kubectl commands you want"

helm:
  image: alpine/helm:latest
  script:
    - helm version
    - echo "Now you can use helm commands you want"
💡
It is recommended to use specific version tags for Docker images. For example, use bitnami/kubectl:1.29.6 and alpine/helm:3.15.2. This ensures consistency, stability, and predictability, preventing issues that can arise from changes in the latest tag.

Conclusion

Deploying applications to Kubernetes using GitLab CI/CD streamlines your DevOps workflow, allowing you to concentrate on developing outstanding applications. Happy deploying!

Read more...