Role and Binding
Understanding RBAC in Kubernetes
Role Types
Role Type |
Scope |
Description |
Role |
Namespace-specific |
Defines permissions within a single namespace |
ClusterRole |
Cluster-wide |
Defines permissions across the entire cluster |
Role Definition Example
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
namespace: default
name: pod-reader
rules:
- apiGroups: [""]
resources: ["pods"]
verbs: ["get", "watch", "list"]
Binding Types
graph TD
A[Role Binding] --> B[Namespace-specific Permissions]
C[Cluster Role Binding] --> D[Cluster-wide Permissions]
RoleBinding Example
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: read-pods
namespace: default
subjects:
- kind: ServiceAccount
name: my-service-account
namespace: default
roleRef:
kind: Role
name: pod-reader
apiGroup: rbac.authorization.k8s.io
Permission Verbs
Verb |
Description |
get |
Retrieve a resource |
list |
List multiple resources |
create |
Create a resource |
update |
Modify a resource |
delete |
Remove a resource |
Practical Implementation
## Create service account
kubectl create serviceaccount app-service-account
## Create role
kubectl create role app-reader --verb=get --verb=list --resource=pods
## Bind role to service account
kubectl create rolebinding app-reader-binding \
--role=app-reader \
--serviceaccount=default:app-service-account
ClusterRole and ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: secret-reader
rules:
- apiGroups: [""]
resources: ["secrets"]
verbs: ["get", "watch", "list"]
Best Practices for LabEx Kubernetes Environments
- Apply least privilege principle
- Use specific roles instead of broad permissions
- Regularly audit and review role bindings
- Separate concerns with distinct roles
Verification Commands
## List roles
kubectl get roles
## Describe role bindings
kubectl describe rolebindings
## Check service account permissions
kubectl auth can-i list pods --as=system:serviceaccount:default:app-service-account
By understanding roles and bindings, developers can implement fine-grained access control in Kubernetes, ensuring secure and controlled resource management.