Namespaced Role and RoleBinding
Role and RoleBinding are used to set permissions within particular namespace. If we need to permissions across namespaces, look cluster role and bindings.
To set permissions, we need to create Role object first and then to assign that role to user, we need to create RoleBinding object. These object requires apiVersion to be rbac.authorization.k8s.io/v1
Role
developer-role.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: developer
namespace: learning
rules:
- apiGroups: [""]
resources: ["pods"]
verbs: ["create", "list", "delete", "get"]
- apiGroups: [""]
resources: ["configmaps"]
verbs: ["create"]Role resource file can define multiple rules in rules section. rules section comprises:
apiGroupscontains a list of apiGroups (for core we keep it empty and specify for named api groups).resourcesare the resources in specifiedapiGroups.verbsare the actions can be applied on the resources.
If we want to name some specific resource, we can use rules.resourceNames field as shown below,
rules:
- apiGroups: [""]
resources: ["pods"]
resourceNames: ["pod-1", "pod-2"]
verbs: ["create", "list", "delete", "get"]Now user can only be able to access pods pod-1 and pod-2.
Role Binding
RoleBinding grants permissions within a specific namespace, defined by its metadata.namespace.
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: devuser-developer-binding
namespace: learning
subjects:
- kind: User
name: devuser
apiGroup: rbac.authorization.k8s.io
roleRef:
name: developer
kind: Role
apiGroup: rbac.authorization.k8s.iosubjects can be the users, service accounts, and groups which we need to have permissions for. There can be multiple entries in subjects.
roleRef is the reference to the role.
Tip
We can check if user is can access particular resource using command
kubectl auth can-i get pods -n default --as dev-user
kubectlcan reply withyesorno. For service accounts, we can do as follows,k auth can-i create deployments --as "system:serviceaccount:learning:nginx-controller-sa" -n learning