Kubernetes Roles and ClusterRoles
Introduction
In Kubernetes, Role-Based Access Control (RBAC) is a method for regulating access to resources based on the roles of individual users within an organization. This lesson focuses on two critical components of RBAC: Roles and ClusterRoles.
Key Concepts
- **Role**: Defines a set of permissions within a specific namespace.
- **ClusterRole**: Defines permissions cluster-wide, applicable across all namespaces.
- **RoleBinding**: Grants the permissions defined in a Role to a user or set of users within a specific namespace.
- **ClusterRoleBinding**: Grants the permissions defined in a ClusterRole to a user or set of users across all namespaces.
Roles
Roles are used to grant access to resources within a specified namespace. For instance, a Role can grant permissions to read pods, create deployments, or delete services within that namespace.
Example Role YAML
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
namespace: example-namespace
name: example-role
rules:
- apiGroups: [""]
resources: ["pods"]
verbs: ["get", "watch", "list"]
ClusterRoles
ClusterRoles extend the concept of Roles by allowing permissions to be applied across the entire cluster. ClusterRoles can be used to define permissions for cluster-wide resources or to allow access to specific namespaces.
Example ClusterRole YAML
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: example-clusterrole
rules:
- apiGroups: [""]
resources: ["pods", "services"]
verbs: ["get", "watch", "list", "create", "delete"]
Creating Roles and ClusterRoles
- Create a Role or a ClusterRole YAML file as shown in the examples above.
- Apply the Role or ClusterRole using the following command:
- Create a RoleBinding or ClusterRoleBinding to bind the Role or ClusterRole to a user/group/service account.
kubectl apply -f .yaml
Example RoleBinding YAML
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: example-rolebinding
namespace: example-namespace
subjects:
- kind: User
name: example-user
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: Role
name: example-role
apiGroup: rbac.authorization.k8s.io
Best Practices
- Least Privilege: Always grant the minimum permissions necessary for a user to perform their job.
- Namespace-specific Roles: Use Roles for namespace-specific access; use ClusterRoles when broader access is needed.
- Version Control: Store your RBAC configurations in version control systems for auditing and tracking changes.
FAQ
What is the difference between Role and ClusterRole?
A Role defines permissions within a specific namespace, while a ClusterRole defines permissions that can apply across the entire cluster.
Can a ClusterRole be used in a specific namespace?
Yes, a ClusterRole can be bound to a specific namespace using a RoleBinding.
How do I check the permissions of a Role or ClusterRole?
You can use the command kubectl describe role
or kubectl describe clusterrole
.