GitLab has strong Kubernetes integration. Unfortunately, GitLab has its own idea of how apps are deployed in the cluster. This is not necessarily the method of choice, especially for existing clusters. But you can reach your goal very easily without the existing integration. And with RBAC you can secure your CI job so that it is not allowed to do more than is absolutely necessary.
First we need a deployment (configurations for service, ingress, etc. omitted).
The name of the deployment
my-app is important, we will need that later.
In order for GitLab to have access to the deployment, we have to create a
ServieAccount and set up the necessary authorizations.
verbs: ["patch"] is required to update the deployment.
verbs: ["get", "list", "watch"] are then required for subsequent deployment monitoring using
kubectl rollout status. If you do not want to wait for the rollout, the verbs can also be omitted.
Now we need the access data of the service account.
We are interested in the name of the Secret, in this case
Now we need to get the credentials for the service account.
All we need is the
token from the
data section. But before we can create the Kubernetes configuration, we have to decode the token. This is Base64 encoded, but we need the plain token.
Now we have everything we need.
ca.crt `EdAGjzRz.. and the decoded token
Now we create a Kubernetes configuration.
Remember to adjust the other values (server, namespace, etc.) to your needs.
The configuration can be tested with a simple
kubectl get deployment.
If everything worked up to this point, we can now create the CI job.
By changing the
commitRef label, the job ensures that Kubernetes rolls out the deployment again. This is interesting, for example, if the Docker Image always uses the
latest tag. If version tags are used, the image name should be updated instead. The patch may have to be adapted to your own needs.
Last but not least, we have to bring the Kubernetes configuration into the GitLab CI. Thanks to a new GitLab CI feature, this is very convenient. Since GitLab 11.11, variables can also be stored as files, which makes it extremely easy to provide the Kubernetes configuration.
In the CI configuration you simply create a variable type file. The key is
KUBECONFIG and as value we enter the content of the previously created
With the next CI run, the deployment should already work. Please note that this is only a minimal example and must be adapted to your personal needs.