RBAC in Kubernetes
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.
1apiVersion: v1
2kind: ServiceAccount
3metadata:
4 name: debug-sa
5 namespace: default # default namespace
Create a cluster role binding with an exists cluster role named cluster-admin
, you can create one if you want.
1apiVersion: rbac.authorization.k8s.io/v1beta1
2kind: ClusterRoleBinding
3metadata:
4 name: debug-admin-crb
5roleRef:
6 apiGroup: rbac.authorization.k8s.io
7 kind: ClusterRole
8 name: cluster-admin # bind to an exists ClusterRole, you can create one if you want
9subjects:
10- kind: ServiceAccount
11 name: debug-sa
12 namespace: default
Ok, that's all. Create our pod now.
1apiVersion: v1
2kind: Pod
3metadata:
4 name: netshoot
5 namespace: default
6 labels:
7 app: netshoot
8spec:
9 serviceAccountName: debug-sa
10 containers:
11 - image: bitnami/kubectl
12 name: kubectl
13 command:
14 - sleep
15 - "3600"
16 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.
1apiVersion: rbac.authorization.k8s.io/v1
2kind: Role
3metadata:
4 name: debug-role
5rules:
6 - apiGroups: [""]
7 resources:
8 - pods # limit the role only have limit access to pods
9 verbs:
10 - get
11 - list
12 - delete
Create a role binding, to bind the role and the service account.
1apiVersion: rbac.authorization.k8s.io/v1
2kind: RoleBinding
3metadata:
4 name: debug-rb
5subjects:
6 - kind: ServiceAccount
7 name: debug-sa
8roleRef:
9 kind: Role
10 name: debug-role
11 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$ k exec -it netshoot -c 'kubectl' -- /bin/bash
2I have no name!@netshoot:/$ kubectl get pods
3NAME READY STATUS RESTARTS AGE
4netshoot 2/2 Running 0 13m
5
6I have no name!@netshoot:/$ kubectl get svc
7Error from server (Forbidden): services is forbidden: User "system:serviceaccount:default:debug-sa" cannot list resource "services" in API group "" in the namespace "default"
8I have no name!@netshoot:/$
What's the difference between role and cluster role?
- For role, it's limited in a namespace, it only can limit resources inside a namespace.
- Some resource like PV, cluster health, it's not related with a namespace, it's cluster wide, you only can use cluster role to limit them.
- A role binding can bind a role to a service account in an other namespace.