GitLab’s Kubernetes agent is a great tool to deploy your applications directly to a Kubernetes cluster, ensuring the deployed version matches the state of the repository. The repository is the single source of truth.

Prior to the agent, integration with Kubernetes was provided via certificates to access the Kubernetes API. However, this made it necessary for the GitLab Runner to access the API endpoint. Often the endpoint is not accessible from the public internet, therefore out of reach for the Runner. With the agent, the API endpoint can remain protected. The agent connects to GitLab and communicates with the Kubernetes API on your behalf.

So far, so great until you notice that the agent has cluster-admin permission by default. Assume you want to limit the access of the agent to a single (or multiple) namespaces, for example, if multiple apps share the same cluster.

By default, the rbac.create=true option of the helm chart grants the cluster-admin role to the service account created for the agent. The solution is to delete this ClusterRoleBinding and create namespaced RoleBindings for each namespace the agent should manage, tying the service account to the admin role.

Making this even more straightforward, I’ve modified the original agent helm chart to grant namespaced permissions if instructed to do so. To install the agent with access only to namespace namespace_a and namespace_b, simply run:

helm repo add namespaced-gitlab-agent
helm repo update
helm upgrade --install gitlab-agent namespaced-gitlab-agent/gitlab-agent \
    --namespace gitlab-agent \
    --create-namespace \
    --set config.kasAddress='wss://' \
    --set config.token='YOUR.AGENT.TOKEN' \
    --set rbac.namespaces="{namespace_a, namespace_b}"

If you omit the last line, you get the old behaviour with cluster-admin permission.