This article explains how to create and manage Role-Based Access Control in Kubernetes, including roles, role bindings, and verifying user permissions.
In this lesson, we dive into Kubernetes Role-Based Access Control (RBAC), providing step-by-step instructions on how to create and manage roles and role bindings within a namespace. You’ll learn how to define specific permissions for users, bind these permissions to users, and verify their access using kubectl commands.
To start, you need to define a Role object. Create a YAML file (e.g., developer-role.yaml) and set the API version to rbac.authorization.k8s.io/v1 and the kind to Role. In this example, we define a role named “developer” with permissions that allow developers to manage pods and create configmaps. Each permission rule contains three key sections: API groups, resources, and verbs. For resources in the core API group, leave the API group field blank.
Once the role is defined, you need to link a user to this role by creating a RoleBinding. A RoleBinding associates a user with the specified role within a given namespace. In this example, we’ll create a role binding named devuser-developer-binding that assigns the “developer” role to the user dev-user in the default namespace.Below is the YAML definition for the role binding (e.g., devuser-developer-binding.yaml):
Copy
Ask AI
apiVersion: rbac.authorization.k8s.io/v1kind: RoleBindingmetadata: name: devuser-developer-bindingsubjects:- kind: User name: dev-user apiGroup: rbac.authorization.k8s.ioroleRef: kind: Role name: developer apiGroup: rbac.authorization.k8s.io
You can test whether a user has access to specific Kubernetes resources using the kubectl auth can-i command:
Copy
Ask AI
kubectl auth can-i create deployments
Expected output:
Copy
Ask AI
yes
And if you test deleting nodes:
Copy
Ask AI
kubectl auth can-i delete nodes
Expected output:
Copy
Ask AI
no
If you need to simulate actions as another user, use the --as flag. Even though the developer role does not have permission to create deployments, it can create pods:
In some cases, you might want to restrict a user’s permissions to specific resources. For instance, if you need to allow a user to manage only two pods named “blue” and “orange” within a namespace, refine the role rule by including the resourceNames field:
Be cautious when specifying resource names. Only include the exact resources you intend to allow access to, as this will restrict access to other resources of the same type.
This lesson has demonstrated how to set up and manage RBAC in Kubernetes. By creating roles and role bindings, you can control user permissions precisely within a namespace. For further practice, refer to Kubernetes’ official documentation and experiment with real RBAC configurations in your environment.For additional resources, consider these links: