概述
RBAC:Role-Based Access Control,基于角色的访问控制。
Kubernetes
中的所有 API
对象都保存在 Etcd
中的,而对这些API操作都是通过 kube-apiserver
来实现的,这是因为需要kube-apiserver来帮我们完成授权,而在Kubernetes中完成授权的机制就是RBAC。
其中RBAC中的基本概念为:
- Rule:规则,一组属于不同API Group的操作集合;
- Role:角色,用于定义一组对Kubernetes API对象操作的一组规则,作用于当个namespace;
- ClusterRole:集群角色,该角色不受namespace的限制;
- Subject:被作用者,也就是规则作用的对象;
- RoleBinding:将角色和被作用者进行绑定,作用于当个namespace;
- ClusterRoleBinding:将集群角色和作用者进行绑定,不受namespace限制;
Role 和 RoleBinding 作用于 namespace
ClusterRole 和 ClusterRoleBinding 作用于整个集群。
ServiceAccount
什么是 ServiceAccount?
Service Account也是一种账号,但是是给运行在Pod里的进程用的,它为Pod里的进程提供了必要的身份证明。
一个 ServiceAccount 的创建十分简单
示例:
apiVersion: v1
kind: ServiceAccount
metadata:
name: jenuser
namespace: devops
然后我们还要设置集群的权限,最后作用于这个对象:
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: jenkins-cr
rules:
- apiGroups: ["extensions", "apps"]
resources: ["deployments"]
verbs: ["create", "delete", "get", "list", "watch", "patch", "update"]
- apiGroups: [""]
resources: ["services"]
verbs: ["create", "delete", "get", "list", "watch", "patch", "update"]
- apiGroups: [""]
resources: ["pods"]
verbs: ["create","delete","get","list","patch","update","watch"]
- apiGroups: [""]
resources: ["pods/exec"]
verbs: ["create","delete","get","list","patch","update","watch"]
- apiGroups: [""]
resources: ["pods/log"]
verbs: ["get","list","watch"]
- apiGroups: [""]
resources: ["secrets"]
verbs: ["get"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: jenkins-crd
roleRef:
kind: ClusterRole
name: jenkins-cr
apiGroup: rbac.authorization.k8s.io
subjects:
- kind: ServiceAccount
name: jenuser
namespace: devops
这里有几个需要注意的,就是 ClusterRole 要怎么配置,通过观察我们可以发现, ClusterRole 有三部分:
- apiGroups
- resources
- verbs
参考
https://kubernetes.io/zh/docs/reference/access-authn-authz/rbac/
https://kubernetes.io/docs/reference/kubectl/overview/#resource-types