我們今天要談的是昨天有提到的RBAC,其中也會結合部分前天的kubeconfig~
要啟用RBAC就必須先將authorization mode加入RBAC,做法昨天有提過:
kube-apiserver --authorization-mode=Example,RBAC
RBAC的API Group為rbac.authorization.k8s.io,而它包含了四種Objects:
Role:集群中的角色,這個角色會被定義可以對哪些resource做出什麼樣的行為,而這個Role必須屬於某個Namespace。
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
namespace: default
name: pod-reader
rules:
- apiGroups: [""] # "" 代表 core API Group
resources: ["pods"]
verbs: ["get", "watch", "list"]
ClusterRole:與Role相似,差別在於ClusterRole不屬於任何Namespace。
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
# "namespace" 會被忽略,因為 ClusterRoles 不受Namespace限制
name: secret-reader
rules:
- apiGroups: [""]
resources: ["secrets"]
verbs: ["get", "watch", "list"]
RoleBinding:將某個Role和某個Subject綁定,而這個Subject可以是Group、User、ServiceAccount,Group就是User或ServiceAccount的集合,而ServiceAccount就是某些服務。
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: read-pods
namespace: default
subjects:
# 可以指定不只一個的 “subject”
- kind: User
name: jane # "name" 有分大小寫
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: Role
name: pod-reader
apiGroup: rbac.authorization.k8s.io
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: read-secrets
namespace: development
subjects:
- kind: User
name: dave
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: ClusterRole
name: secret-reader
apiGroup: rbac.authorization.k8s.io
ClusterRoleBinding:和RoleBinding相似,只是這邊是綁定ClusterRole。
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: read-secrets-global
subjects:
- kind: Group
name: manager
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: ClusterRole
name: secret-reader
apiGroup: rbac.authorization.k8s.io
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
namespace: default
name: configmap-updater
rules:
- apiGroups: [""]
resources: ["configmaps"]
resourceNames: ["my-configmap"]
verbs: ["update", "get"]
我們也可以設置resourceNames,來讓configmap-updater這個Role只能訪問my-configmap這個ConfigMap。
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
namespace: default
name: example.com-superuser
rules:
- apiGroups: ["example.com"]
resources: ["*"]
verbs: ["*"]
也可以使用 * 來指派example.com這個API Group下的所有資源。
要怎麼知道自己或是其他User是否有權限可以做什麼事呢?
# 是否有權限做這件事要用auth can-i
kubectl auth can-i create deployments
# 會收到 yes or no
# 加上--as dev-user,可以確認dev-user的權限
kubectl auth can-i create deployments --as dev-user