Kubernetes - RBAC & Roles
Updated at 2020-10-06 14:05
Role-based Access Control (RBAC):
- Cluster has service accounts, roles and role bindings.
- Service accounts are entities who act on the cluster e.g.
my-account
. - Roles have permissions; e.g.
my-admin-role
can create pod objects. - Role bindings tell who has that role; e.g.
my-account
hasmy-admin-role
.
Service accounts are a standard way of giving cluster permissions to programs that want to use the Kubernetes API. By default, they will also generate a token that you can use to authenticate.
kubectl create serviceaccount my-service-account
kubectl get serviceaccounts my-service-account -o json
kubectl get secret/`kubectl get sa/my-service-account -o jsonpath='{.secrets[0].name}'` \
-o json
# you might want to use base64 decode the "token", depending how you use it
# | base64 --decode
Check which versions of the role-based authentication API are enabled.
kubectl api-versions | grep rbac
# rbac.authorization.k8s.io/v1
# rbac.authorization.k8s.io/v1beta1
Creating a role:
cat <<EOF | kubectl apply -f -
kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: my-admin-role
namespace: my-namespace
rules:
- apiGroups: [""]
resources: ["namespaces"]
verbs: ["get", "list", "watch"]
- apiGroups: [""]
resources: ["pods"]
verbs: ["*"]
- apiGroups: ["apps", "extensions"]
resources: ["deployments", "deployments/rollback", "deployments/scale"]
verbs: ["create", "delete", "deletecollection", "get", "list", "patch", "update", "watch"]
EOF
Creating a role binding:
kubectl create rolebinding my-admin-role-to-sa-binding \
--role=my-admin-role \
--serviceaccount=my-namespace:my-service-account \
--namespace=my-namespace
Other useful commands:
kubectl describe role my-admin-role
kubectl auth can-i 'create' 'deployments' --as=system:serviceaccount:my-namespace:my-service-account
# returns either yes or no
Cleanup after this RBAC document:
kubectl delete rolebinding/my-admin-role-to-sa-binding
kubectl delete role/my-admin-role
kubectl delete serviceaccount/my-service-account