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.Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
Creating a Role
To start, you need to define a Role object. Create a YAML file (e.g., developer-role.yaml) and set the API version torbac.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.
Remember that roles in Kubernetes are namespace-specific. Ensure the YAML definition targets the correct namespace if needed.
Binding a User to the Role
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 nameddevuser-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):
Verifying Roles and Role Bindings
After creating the role and role binding, you can verify them using the following kubectl commands:-
To list roles:
Example output:
-
To list role bindings:
Example output:
Testing Access Permissions
You can test whether a user has access to specific Kubernetes resources using thekubectl auth can-i command:
--as flag. Even though the developer role does not have permission to create deployments, it can create pods:
--namespace flag if the permissions are scoped accordingly.
Granting Access to Specific Resources
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 theresourceNames 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.