kubectl : Use multiple account accesses

Posted by ZedTuX 0n R00t on January 18, 2019

Kubernetes has released RBAC (Role-based access control) which allows you to manage and restrict user accesses in the cluster.

I decided to create a ServiceAccount in order to limite the access to the cluster when running the tests in the Gitlab CI pipelines.

A ServiceAccount ci restricted to a ci Namespace with a limited list of resources and actions.

To avoid having to wait on a build in order to try running a kubectl command, I configured it in order to get access to the ci ServiceAccount from my local machine.

As it requires some steps, and isn’t really easy to remeber, I decided to write this blog post as a kind of reminder.

Add a context to kubectl

Create the gitlab-ci cluster

First step is to create a cluster and pass the cluster URL :

1
2
$ kubectl config set-cluster gitlab-ci --server=$KUBERNETES_URL
Cluster "gitlab-ci" set.

If you have the cluster CA as a file locally, you can pass it to the --certificate-authority flag, but in my case I don’t, so I will reuse the same trick as the one I described in my previous post kubectl : x509: certificate signed by unknown authority and pass the base64 string directly :

1
2
$ kubectl config set clusters.gitlab-ci.certificate-authority-data $KUBERNETES_CA --set-raw-bytes=false
Property "clusters.gitlab-ci.certificate-authority-data" set.

Now let’s add the user :

1
2
$ kubectl config set-credentials gitlab-ci --token=$KUBERNETES_TOKEN
User "gitlab-ci" set.

And finally let’s connect all this together as a ci context :

1
2
$ kubectl config set-context ci --cluster=gitlab-ci --user=gitlab-ci --namespace=ci
Context "ci" created.

Last but not least let’s check the config :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
$ kubectl config view
clusters:
- cluster:
    certificate-authority-data: DATA+OMITTED
    server: https://<UUID>.k8s.ondigitalocean.com
  name: do-fra1-k8s-gitlab
- cluster:
    certificate-authority-data: DATA+OMITTED
    server: https://<UUID>.k8s.ondigitalocean.com
  name: gitlab-ci
contexts:
- context:
    cluster: gitlab-ci
    user: gitlab-ci
  name: ci
- context:
    cluster: do-fra1-k8s-gitlab
    user: do-fra1-k8s-gitlab-admin
  name: do-fra1-k8s-gitlab
current-context: do-fra1-k8s-gitlab
kind: Config
preferences: {}
users:
- name: do-fra1-k8s-gitlab-admin
  user:
    client-certificate-data: REDACTED
    client-key-data: REDACTED
- name: gitlab-ci
  user:
    token: REDACTED

Use the added context

Now to switch to the ci context you just have to :

1
2
$ kubectl config use-context ci
Switched to context "ci".

Now you are logged in as the ci ServiceAccount and your requests will be executed in the ci Namespace by default (you can override it with the --namespace flag).

Delete the context

In the case you’d like to delete the added ci context :

1
2
$ kubectl config delete-context ci
deleted context ci from /Users/zedtux/.kube/config