How to Deploy to Kubernetes with kubectl in GitLab CI
Wire a kubeconfig into a CI/CD variable and run kubectl set image plus rollout status to ship and verify.
Store the cluster kubeconfig as a masked, base64-encoded variable, decode it at job start, then apply the new image and wait for the rollout to converge.
Apply and wait for rollout
Decode the kubeconfig, update the deployment image, and block until the rollout succeeds so a crash-looping pod fails the job.
.gitlab-ci.yml
deploy:
image: bitnami/kubectl:latest
environment:
name: production
script:
- echo "$KUBECONFIG_B64" | base64 -d > "$KUBECONFIG"
- kubectl set image deployment/web web="$CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA"
- kubectl rollout status deployment/web --timeout=120s
variables:
KUBECONFIG: /tmp/kubeconfig
rules:
- if: $CI_COMMIT_BRANCH == "main"Notes
- Store KUBECONFIG_B64 as a masked, protected CI/CD variable so it only exposes on protected branches.
- rollout status with --timeout turns a failed deploy into a failed pipeline instead of a silent bad release.
- Pair this with environment: name: production to get GitLab environment tracking and rollback buttons.
Related guides
How to Run a Trivy Scan in GitLab CIScan a container image for vulnerabilities in GitLab CI with Trivy, fail the pipeline on HIGH or CRITICAL fin…
How to Set Up a Merge Request Pipeline in GitLab CIConfigure merge request pipelines in GitLab CI with workflow:rules so jobs run on the MR context, avoiding du…