How to Deploy to Kubernetes With kubectl in GitLab CI/CD
kubectl set image triggers a rolling update and kubectl rollout status makes the job wait until it succeeds.
Point kubectl at your cluster, run kubectl set image to bump the Deployment to the new tag, then block on kubectl rollout status so a stuck rollout fails the pipeline.
Steps
- Provide a kubeconfig via a masked file variable.
- Run
kubectl set image deployment/<name> <container>=<image>. - Wait with
kubectl rollout statusand a timeout. - Scope the job to the default branch.
.gitlab-ci.yml
.gitlab-ci.yml
deploy:
stage: deploy
image: bitnami/kubectl:1.30
variables:
KUBECONFIG: /tmp/kubeconfig
rules:
- if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'
script:
- echo "$KUBE_CONFIG_B64" | base64 -d > "$KUBECONFIG"
- kubectl set image deployment/myapp myapp="$CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA" -n production
- kubectl rollout status deployment/myapp -n production --timeout=120sGotchas
- Store the kubeconfig as a masked, protected file variable so it never prints to logs.
- Without
rollout statusthe job passes even when the new pods crash-loop.
Related guides
How to Deploy With Helm in GitLab CI/CDDeploy a Helm chart from GitLab CI/CD with helm upgrade --install, passing the image tag from the pipeline an…
How to Roll Back a Deployment With GitLab CI/CDRoll back a deployment in GitLab CI/CD with a manual rollback job that redeploys a previous image tag passed…