Defining Roles and Permissions in Kubernetes
In Kubernetes, Roles and ClusterRoles are used to define the permissions that can be granted to users, groups, or service accounts. Roles define permissions within a specific namespace, while ClusterRoles define permissions that span across the entire Kubernetes cluster.
graph TD
A[Kubernetes Cluster] --> B[Roles]
A[Kubernetes Cluster] --> C[ClusterRoles]
B --> D[Namespace Permissions]
C --> E[Cluster-wide Permissions]
When defining a Role or ClusterRole, you specify the API groups, resources, and verbs that the role is allowed to perform. For example, the following Role grants the ability to get, list, and watch Pods in the default
namespace:
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
namespace: default
name: pod-reader
rules:
- apiGroups: [""] ## "" indicates the core API group
resources: ["pods"]
verbs: ["get", "list", "watch"]
Similarly, the following ClusterRole grants the ability to manage Secrets across the entire Kubernetes cluster:
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: secret-manager
rules:
- apiGroups: [""]
resources: ["secrets"]
verbs: ["create", "update", "delete", "get", "list"]
Once you have defined the necessary Roles and ClusterRoles, you can use RoleBindings and ClusterRoleBindings to associate them with specific subjects (users, groups, or service accounts). For example, the following RoleBinding grants the pod-reader
Role to the alice
user in the default
namespace:
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: read-pods
namespace: default
subjects:
- kind: User
name: alice ## Name is case-sensitive
roleRef:
kind: Role
name: pod-reader
apiGroup: rbac.authorization.k8s.io
By carefully defining and managing Roles, ClusterRoles, RoleBindings, and ClusterRoleBindings, you can ensure that users, groups, and service accounts have the appropriate level of access to Kubernetes resources, helping to maintain the security and integrity of your Kubernetes cluster.