wd and cc

— Happy every day

RBAC in Kubernetes

Posted at — May 18, 2020

How to give a pod the access to run kubectl to create pods or configmaps? It's very simple.

Every pods has to bind to a service account, it will be default, if you haven't specify one. And by default, this account didn't have any access to the kubernetes API.

First, create a service account.

1
2
3
4
5
apiVersion: v1
kind: ServiceAccount
metadata:
  name: debug-sa
  namespace: default  # default namespace

Create a cluster role binding with an exists cluster role named cluster-admin, you can create one if you want.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRoleBinding
metadata:
  name: debug-admin-crb
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: cluster-admin # bind to an exists ClusterRole, you can create one if you want
subjects:
- kind: ServiceAccount
  name: debug-sa
  namespace: default

Ok, that's all. Create our pod now.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
apiVersion: v1
kind: Pod
metadata:
  name: netshoot
  namespace: default
  labels:
    app: netshoot
spec:
  serviceAccountName: debug-sa
  containers:
  - image: bitnami/kubectl
    name: kubectl
    command:
      - sleep
      - "3600"
  restartPolicy: Always

Now, your pods have the cluster-admin access to visit you API resources. What's if I only need to give the pod the access to list pods?

First, create a role, with limited access to pods. This role can't visit other resource other than pods.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: debug-role
rules:
  - apiGroups: [""]
    resources:
      - pods # limit the role only have limit access to pods
    verbs:
      - get
      - list
      - delete

Create a role binding, to bind the role and the service account.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: debug-rb
subjects:
  - kind: ServiceAccount
    name: debug-sa
roleRef:
  kind: Role
  name: debug-role
  apiGroup: rbac.authorization.k8s.io

And then recreate your pod with this service account. Don't forget to delete the privious cluter role binding for this service account.

1
2
3
4
5
6
7
8
$ k exec -it netshoot -c 'kubectl' -- /bin/bash
I have no [email protected]:/$ kubectl get pods
NAME                                          READY   STATUS    RESTARTS   AGE
netshoot                                      2/2     Running   0          13m

I have no [email protected]:/$ kubectl get svc
Error from server (Forbidden): services is forbidden: User "system:serviceaccount:default:debug-sa" cannot list resource "services" in API group "" in the namespace "default"
I have no [email protected]:/$

What's the difference between role and cluster role?

comments powered by Disqus