概述

RBAC:Role-Based Access Control,基于角色的访问控制。

Kubernetes 中的所有 API 对象都保存在 Etcd 中的,而对这些API操作都是通过 kube-apiserver 来实现的,这是因为需要kube-apiserver来帮我们完成授权,而在Kubernetes中完成授权的机制就是RBAC。

其中RBAC中的基本概念为:

  1. Rule:规则,一组属于不同API Group的操作集合;
  2. Role:角色,用于定义一组对Kubernetes API对象操作的一组规则,作用于当个namespace;
  3. ClusterRole:集群角色,该角色不受namespace的限制;
  4. Subject:被作用者,也就是规则作用的对象;
  5. RoleBinding:将角色和被作用者进行绑定,作用于当个namespace;
  6. ClusterRoleBinding:将集群角色和作用者进行绑定,不受namespace限制;

Role 和 RoleBinding 作用于 namespace
ClusterRole 和 ClusterRoleBinding 作用于整个集群。

ServiceAccount

什么是 ServiceAccount?
Service Account也是一种账号,但是是给运行在Pod里的进程用的,它为Pod里的进程提供了必要的身份证明。

一个 ServiceAccount 的创建十分简单
示例:

  1. apiVersion: v1
  2. kind: ServiceAccount
  3. metadata:
  4. name: jenuser
  5. namespace: devops

然后我们还要设置集群的权限,最后作用于这个对象:

  1. ---
  2. apiVersion: rbac.authorization.k8s.io/v1
  3. kind: ClusterRole
  4. metadata:
  5. name: jenkins-cr
  6. rules:
  7. - apiGroups: ["extensions", "apps"]
  8. resources: ["deployments"]
  9. verbs: ["create", "delete", "get", "list", "watch", "patch", "update"]
  10. - apiGroups: [""]
  11. resources: ["services"]
  12. verbs: ["create", "delete", "get", "list", "watch", "patch", "update"]
  13. - apiGroups: [""]
  14. resources: ["pods"]
  15. verbs: ["create","delete","get","list","patch","update","watch"]
  16. - apiGroups: [""]
  17. resources: ["pods/exec"]
  18. verbs: ["create","delete","get","list","patch","update","watch"]
  19. - apiGroups: [""]
  20. resources: ["pods/log"]
  21. verbs: ["get","list","watch"]
  22. - apiGroups: [""]
  23. resources: ["secrets"]
  24. verbs: ["get"]
  25. ---
  26. apiVersion: rbac.authorization.k8s.io/v1
  27. kind: ClusterRoleBinding
  28. metadata:
  29. name: jenkins-crd
  30. roleRef:
  31. kind: ClusterRole
  32. name: jenkins-cr
  33. apiGroup: rbac.authorization.k8s.io
  34. subjects:
  35. - kind: ServiceAccount
  36. name: jenuser
  37. namespace: devops

这里有几个需要注意的,就是 ClusterRole 要怎么配置,通过观察我们可以发现, ClusterRole 有三部分:

  1. apiGroups
  2. resources
  3. verbs

参考

https://kubernetes.io/zh/docs/reference/access-authn-authz/rbac/
https://kubernetes.io/docs/reference/kubectl/overview/#resource-types