In part 19 you installed Traefik with a ServiceAccount, a ClusterRole and a ClusterRoleBinding, and we promised to explain them. This is that part. You will learn how the API server decides whether a request is allowed, give a Pod its own identity, grant it exactly the access it needs, and check each permission from the command line before anything breaks. You need the kind cluster from part 3 and the k8s-from-zero namespace from part 4. We tested every step on kind v0.33.0 (node image v1.37.0) with kubectl v1.37.2.
What you will build
A Pod named inspector asks the API server, from inside the cluster, for the list of Pods in its namespace. At first it is refused with 403 Forbidden. You then create a Role and a RoleBinding, and the same request returns the list. Along the way you grant it a built-in role in one namespace and a cluster-wide permission to read nodes, and you check each grant with kubectl auth can-i.
Every request is authenticated, then authorized
Each request to the API server passes two checks (Authorization). Authentication answers “who are you”: a client certificate, a bearer token or another configured method turns the request into a user name and a list of groups. Authorization answers “may you do this”: an authorizer, on kind and most clusters RBAC (role-based access control), compares the request’s verb, resource, API group and namespace with the rules granted to that user and those groups.
Ask the API server who you are with kubectl auth whoami. On kind your kubeconfig holds a client certificate for an admin user:
kubectl auth whoamiExplain this command
kubectl auth whoamikubectlThe Kubernetes command-line client. Subcommands and flags are documented under kubernetes.io/docs/reference/kubectl/.authThe command group for authorization and identity checks. It includes can-i and whoami.whoamiShow who you are to the cluster. The whoami docs say it checks who you are and your attributes (groups, extra); with --as, it shows the impersonated subject.
ATTRIBUTE VALUE
Username kubernetes-admin
Groups [kubeadm:cluster-admins system:authenticated]
...
The group kubeadm:cluster-admins is bound to the built-in ClusterRole cluster-admin, which allows everything. That is why every command so far in this series has worked.
Kubernetes has no User object. Users and groups come from whatever authenticates them, such as certificates or an identity provider. Workloads are different: they get a ServiceAccount, a namespaced API object, and its identity looks like system:serviceaccount:NAMESPACE:NAME (Service Accounts).
RBAC itself has four object kinds (Using RBAC Authorization):
- A Role is a list of rules in one namespace. Each rule names
apiGroups(""is the core group of Pods, Services and ConfigMaps; Deployments live inapps),resourcesandverbs(get,list,watch,create,update,patch,delete). - A ClusterRole is the same, but not namespaced. It can describe cluster-scoped resources such as nodes, or be reused in many namespaces.
- A RoleBinding grants a Role or a ClusterRole to subjects (users, groups, ServiceAccounts) inside the binding’s namespace.
- A ClusterRoleBinding grants a ClusterRole in every namespace and on cluster-scoped resources.
Permissions are purely additive. There are no deny rules, so a subject with no binding can do nothing beyond a few discovery calls, and the only way to take access away is to remove a grant.
The binding decides where the rules apply
The rules say what may be done; the binding says where. A RoleBinding that references a ClusterRole grants those rules only inside the RoleBinding’s namespace. That is how the built-in roles are meant to be used: admin, edit and view are ClusterRoles intended to be granted per namespace with a RoleBinding, while cluster-admin is the super-user role. view gives read access to most objects in a namespace but not to Secrets, because reading Secrets would expose ServiceAccount tokens and other credentials (Using RBAC Authorization).
Two rules of the API are worth knowing before they surprise you. A binding’s roleRef cannot be changed after creation; to point a binding at a different role, delete it and create a new one. And a ClusterRoleBinding can only reference a ClusterRole. We tried a ClusterRoleBinding with kind: Role in its roleRef, and the API refused it:
The ClusterRoleBinding "try-role-in-crb" is invalid: roleRef.kind: Unsupported value: "Role": supported values: "ClusterRole"
A ServiceAccount is a Pod’s identity
Every namespace has a ServiceAccount named default, and a Pod that does not name one gets it. The default ServiceAccount has no permissions beyond API discovery (Service Accounts). Give each app its own ServiceAccount with spec.serviceAccountName, so that you can grant it exactly what it needs and nothing leaks to other Pods in the namespace.
The credential arrives as a file. The ServiceAccount admission controller adds a projected volume named kube-api-access-<suffix> to the Pod, and the kubelet fills it with three files under /var/run/secrets/kubernetes.io/serviceaccount: token, ca.crt (from the ConfigMap kube-root-ca.crt that exists in every namespace) and namespace (Managing Service Accounts). The token is a JWT (a signed JSON document) that the kubelet gets from the TokenRequest API. It is bound to this Pod, has the API server as its audience, and the kubelet replaces it when it is older than 80 percent of its lifetime or older than 24 hours (Configure Service Accounts for Pods). Long-lived token Secrets are the old mechanism; since v1.24 they are no longer created automatically.
A Pod that never talks to the API server does not need the token at all. Set automountServiceAccountToken: false in the Pod spec (or on the ServiceAccount; the Pod setting wins).
Try it: give a Pod exactly the access it needs
- Create the ServiceAccount and a Pod that uses it. The image has curl in it. Save this as
inspector.yaml:
apiVersion: v1
kind: ServiceAccount
metadata:
name: inspector
namespace: k8s-from-zero
---
apiVersion: v1
kind: Pod
metadata:
name: inspector
namespace: k8s-from-zero
labels:
app.kubernetes.io/name: inspector
spec:
serviceAccountName: inspector
containers:
- name: curl
image: curlimages/curl:8.23.0
command: ["sleep", "3600"]
kubectl apply -f inspector.yaml
kubectl wait --for=condition=Ready pod/inspector -n k8s-from-zero --timeout=60s
kubectl get pod inspector -n k8s-from-zero -o jsonpath='{.spec.serviceAccountName}{"\n"}'
kubectl exec -n k8s-from-zero inspector -- ls /var/run/secrets/kubernetes.io/serviceaccountExplain this command
kubectl apply -f inspector.yaml
kubectl wait --for=condition=Ready pod/inspector -n k8s-from-zero --timeout=60s
kubectl get pod inspector -n k8s-from-zero -o jsonpath='{.spec.serviceAccountName}{"\n"}'
kubectl exec -n k8s-from-zero inspector -- ls /var/run/secrets/kubernetes.io/serviceaccountkubectlThe Kubernetes command-line client. Subcommands and flags are documented under kubernetes.io/docs/reference/kubectl/.applyApply a configuration to a resource by file name or stdin. The apply docs say the resource is created if it does not exist yet. JSON and YAML are accepted.-fShort form of --filename. The file, directory or URL that contains the configuration to apply.inspector.yamlThe file named by --filename. apply creates the objects or updates them to match this file.
Explain this command
kubectl apply -f inspector.yaml
kubectl wait --for=condition=Ready pod/inspector -n k8s-from-zero --timeout=60s
kubectl get pod inspector -n k8s-from-zero -o jsonpath='{.spec.serviceAccountName}{"\n"}'
kubectl exec -n k8s-from-zero inspector -- ls /var/run/secrets/kubernetes.io/serviceaccountkubectlThe Kubernetes command-line client. Subcommands and flags are documented under kubernetes.io/docs/reference/kubectl/.waitWait for a condition on one or more resources.--for=condition=ReadyThe condition to wait for. Here kubectl waits until the condition named after --for is met.pod/inspectorThe resource written as type/name: pod/inspector.-nShort form of --namespace. If present, the namespace scope for this CLI request.k8s-from-zeroThe namespace name.--timeout=60sHow long to wait before giving up. This command passes 60s.
Explain this command
kubectl apply -f inspector.yaml
kubectl wait --for=condition=Ready pod/inspector -n k8s-from-zero --timeout=60s
kubectl get pod inspector -n k8s-from-zero -o jsonpath='{.spec.serviceAccountName}{"\n"}'
kubectl exec -n k8s-from-zero inspector -- ls /var/run/secrets/kubernetes.io/serviceaccountkubectlThe Kubernetes command-line client. Subcommands and flags are documented under kubernetes.io/docs/reference/kubectl/.getDisplay one or many resources. kubectl get prints a table of the most important information about the resources you name.podThe resource type to display. kubectl get points you to kubectl api-resources for the full list of types the server supports.inspectorThe object name.-nShort form of --namespace. If present, the namespace scope for this CLI request.k8s-from-zeroThe namespace name.-oShort form of --output. It selects the output format. For get, the formats include json, yaml, name, jsonpath, custom-columns and wide.jsonpath='{.spec.serviceAccountName}{"\n"}'A jsonpath output format. The get docs say jsonpath prints the fields the expression selects. The lesson uses this path to print the fields named in the command.
Explain this command
kubectl apply -f inspector.yaml
kubectl wait --for=condition=Ready pod/inspector -n k8s-from-zero --timeout=60s
kubectl get pod inspector -n k8s-from-zero -o jsonpath='{.spec.serviceAccountName}{"\n"}'
kubectl exec -n k8s-from-zero inspector -- ls /var/run/secrets/kubernetes.io/serviceaccountkubectlThe Kubernetes command-line client. Subcommands and flags are documented under kubernetes.io/docs/reference/kubectl/.execExecute a command in a container. The synopsis is kubectl exec (POD | TYPE/NAME) [-c CONTAINER] [flags] -- COMMAND [args...].-nShort form of --namespace. If present, the namespace scope for this CLI request.k8s-from-zeroThe namespace name.inspectorThe object name.--Ends kubectl's flags. The exec examples say to use two dashes so the command's own flags are read as that command's flags.lsList the files in a directory. It runs inside the container./var/run/secrets/kubernetes.io/serviceaccountThe directory where Kubernetes mounts the Pod's ServiceAccount files: token, ca.crt and namespace.
serviceaccount/inspector created
pod/inspector created
pod/inspector condition met
inspector
ca.crt
namespace
token
- Check the identity and its permissions from outside.
--asmakes kubectl impersonate another subject; your admin user is allowed to do that:
kubectl auth whoami --as=system:serviceaccount:k8s-from-zero:inspector
kubectl auth can-i list pods -n k8s-from-zero --as=system:serviceaccount:k8s-from-zero:inspectorExplain this command
kubectl auth whoami --as=system:serviceaccount:k8s-from-zero:inspector
kubectl auth can-i list pods -n k8s-from-zero --as=system:serviceaccount:k8s-from-zero:inspectorkubectlThe Kubernetes command-line client. Subcommands and flags are documented under kubernetes.io/docs/reference/kubectl/.authThe command group for authorization and identity checks. It includes can-i and whoami.whoamiShow who you are to the cluster. The whoami docs say it checks who you are and your attributes (groups, extra); with --as, it shows the impersonated subject.--as=system:serviceaccount:k8s-from-zero:inspectorThe subject to impersonate, written as a service account: system:serviceaccount:NAMESPACE:NAME.
Explain this command
kubectl auth whoami --as=system:serviceaccount:k8s-from-zero:inspector
kubectl auth can-i list pods -n k8s-from-zero --as=system:serviceaccount:k8s-from-zero:inspectorkubectlThe Kubernetes command-line client. Subcommands and flags are documented under kubernetes.io/docs/reference/kubectl/.authThe command group for authorization and identity checks. It includes can-i and whoami.can-iCheck whether an action is allowed. The docs say kubectl auth can-i VERB [TYPE | TYPE/NAME | NONRESOURCEURL].listThe verb to check: may the subject list objects of this type?podsThe resource type.-nShort form of --namespace. If present, the namespace scope for this CLI request.k8s-from-zeroThe namespace name.--as=system:serviceaccount:k8s-from-zero:inspectorThe subject to impersonate, written as a service account: system:serviceaccount:NAMESPACE:NAME.
ATTRIBUTE VALUE
Username system:serviceaccount:k8s-from-zero:inspector
Groups [system:serviceaccounts system:serviceaccounts:k8s-from-zero system:authenticated]
no
- Call the API from inside the Pod. This script reads the three mounted files and asks for the Pods in the Pod’s own namespace.
kubernetes.default.svcis the Service in front of the API server that every cluster has. Save it asask.sh:
# Run inside the inspector Pod: list Pods in its own namespace through the API
SA=/var/run/secrets/kubernetes.io/serviceaccount
NS=$(cat $SA/namespace)
curl -s --cacert $SA/ca.crt -H "Authorization: Bearer $(cat $SA/token)" \
https://kubernetes.default.svc/api/v1/namespaces/$NS/podsExplain this command
# Run inside the inspector Pod: list Pods in its own namespace through the API
SA=/var/run/secrets/kubernetes.io/serviceaccount
NS=$(cat $SA/namespace)
curl -s --cacert $SA/ca.crt -H "Authorization: Bearer $(cat $SA/token)" \
https://kubernetes.default.svc/api/v1/namespaces/$NS/podsSA=/var/run/secrets/kubernetes.io/serviceaccountA shell variable, SA, set to the directory where the ServiceAccount files are mounted.
Explain this command
# Run inside the inspector Pod: list Pods in its own namespace through the API
SA=/var/run/secrets/kubernetes.io/serviceaccount
NS=$(cat $SA/namespace)
curl -s --cacert $SA/ca.crt -H "Authorization: Bearer $(cat $SA/token)" \
https://kubernetes.default.svc/api/v1/namespaces/$NS/podsNS=$(cat $SA/namespace)A shell variable, NS, set to the Pod's namespace, read from the namespace file in that directory.
Explain this command
# Run inside the inspector Pod: list Pods in its own namespace through the API
SA=/var/run/secrets/kubernetes.io/serviceaccount
NS=$(cat $SA/namespace)
curl -s --cacert $SA/ca.crt -H "Authorization: Bearer $(cat $SA/token)" \
https://kubernetes.default.svc/api/v1/namespaces/$NS/podscurlA command-line HTTP client. Flags after it control the request and where the response is written.-sSilent mode: hide the progress meter.--cacertWith curl, check the server's certificate against this CA file.$SA/ca.crtThe cluster CA certificate, mounted next to the token.-HWith curl, add a request header. The header text follows."Authorization: Bearer $(cat $SA/token)"The Authorization header. $(cat $SA/token) inserts the ServiceAccount token, so the API server sees the Pod's identity.https://kubernetes.default.svc/api/v1/namespaces/$NS/podsThe API server's in-cluster address, asking for the list of Pods in namespace $NS.
kubectl exec -n k8s-from-zero -i inspector -- sh < ask.shExplain this command
kubectl exec -n k8s-from-zero -i inspector -- sh < ask.shkubectlThe Kubernetes command-line client. Subcommands and flags are documented under kubernetes.io/docs/reference/kubectl/.execExecute a command in a container. The synopsis is kubectl exec (POD | TYPE/NAME) [-c CONTAINER] [flags] -- COMMAND [args...].-nShort form of --namespace. If present, the namespace scope for this CLI request.k8s-from-zeroThe namespace name.-iShort form of --stdin. Pass stdin through to the container.inspectorThe object name.--Ends kubectl's flags. The exec examples say to use two dashes so the command's own flags are read as that command's flags.shA shell. The command that follows runs inside it.<A shell redirect. The local file that follows becomes the standard input of sh in the container.ask.shThe script on your machine. It reaches the container's sh through stdin, so nothing is copied into the Pod.
{
"kind": "Status",
"apiVersion": "v1",
"metadata": {},
"status": "Failure",
"message": "pods is forbidden: User \"system:serviceaccount:k8s-from-zero:inspector\" cannot list resource \"pods\" in API group \"\" in the namespace \"k8s-from-zero\"",
"reason": "Forbidden",
"details": {
"kind": "pods"
},
"code": 403
}
Read the message as the RBAC sentence: who (system:serviceaccount:k8s-from-zero:inspector), what (list), which (pods in API group ""), where (k8s-from-zero). Every RBAC error has this shape, and it tells you exactly which rule is missing.
- Grant it. Save this as
pod-reader.yaml:
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: pod-reader
namespace: k8s-from-zero
rules:
- apiGroups: [""] # "" is the core API group: Pods, Services, ConfigMaps...
resources: ["pods"]
verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: inspector-reads-pods
namespace: k8s-from-zero
subjects:
- kind: ServiceAccount
name: inspector
namespace: k8s-from-zero
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: pod-reader
You can also generate the same objects: kubectl create role pod-reader --verb=get,list,watch --resource=pods -n k8s-from-zero --dry-run=client -o yaml and kubectl create rolebinding inspector-reads-pods --role=pod-reader --serviceaccount=k8s-from-zero:inspector -n k8s-from-zero --dry-run=client -o yaml print equivalent YAML.
kubectl apply -f pod-reader.yaml
kubectl auth can-i list pods -n k8s-from-zero --as=system:serviceaccount:k8s-from-zero:inspector
kubectl exec -n k8s-from-zero -i inspector -- sh < ask.sh | grep -E '^ "kind"|^ "name"'Explain this command
kubectl apply -f pod-reader.yaml
kubectl auth can-i list pods -n k8s-from-zero --as=system:serviceaccount:k8s-from-zero:inspector
kubectl exec -n k8s-from-zero -i inspector -- sh < ask.sh | grep -E '^ "kind"|^ "name"'kubectlThe Kubernetes command-line client. Subcommands and flags are documented under kubernetes.io/docs/reference/kubectl/.applyApply a configuration to a resource by file name or stdin. The apply docs say the resource is created if it does not exist yet. JSON and YAML are accepted.-fShort form of --filename. The file, directory or URL that contains the configuration to apply.pod-reader.yamlThe file named by --filename. apply creates the objects or updates them to match this file.
Explain this command
kubectl apply -f pod-reader.yaml
kubectl auth can-i list pods -n k8s-from-zero --as=system:serviceaccount:k8s-from-zero:inspector
kubectl exec -n k8s-from-zero -i inspector -- sh < ask.sh | grep -E '^ "kind"|^ "name"'kubectlThe Kubernetes command-line client. Subcommands and flags are documented under kubernetes.io/docs/reference/kubectl/.authThe command group for authorization and identity checks. It includes can-i and whoami.can-iCheck whether an action is allowed. The docs say kubectl auth can-i VERB [TYPE | TYPE/NAME | NONRESOURCEURL].listThe verb to check: may the subject list objects of this type?podsThe resource type.-nShort form of --namespace. If present, the namespace scope for this CLI request.k8s-from-zeroThe namespace name.--as=system:serviceaccount:k8s-from-zero:inspectorThe subject to impersonate, written as a service account: system:serviceaccount:NAMESPACE:NAME.
Explain this command
kubectl apply -f pod-reader.yaml
kubectl auth can-i list pods -n k8s-from-zero --as=system:serviceaccount:k8s-from-zero:inspector
kubectl exec -n k8s-from-zero -i inspector -- sh < ask.sh | grep -E '^ "kind"|^ "name"'kubectlThe Kubernetes command-line client. Subcommands and flags are documented under kubernetes.io/docs/reference/kubectl/.execExecute a command in a container. The synopsis is kubectl exec (POD | TYPE/NAME) [-c CONTAINER] [flags] -- COMMAND [args...].-nShort form of --namespace. If present, the namespace scope for this CLI request.k8s-from-zeroThe namespace name.-iShort form of --stdin. Pass stdin through to the container.inspectorThe object name.--Ends kubectl's flags. The exec examples say to use two dashes so the command's own flags are read as that command's flags.shA shell. The command that follows runs inside it.<A shell redirect. The local file that follows becomes the standard input of sh in the container.ask.shThe script on your machine. It reaches the container's sh through stdin, so nothing is copied into the Pod.|A shell pipe. The output of the command on the left becomes the input of the command on the right.grepShell. Prints input lines that match a pattern.-ETell grep to treat the pattern as an extended regular expression.'^ "kind"|^ "name"'The extended regular expression grep looks for: the kind line and the Pod name lines of the JSON reply.
role.rbac.authorization.k8s.io/pod-reader created
rolebinding.rbac.authorization.k8s.io/inspector-reads-pods created
yes
"kind": "PodList",
"name": "inspector",
The grep keeps only the list’s kind and the Pod names. Now check the edges of the grant. The Role allows reading Pods in one namespace, so deleting them, reading them elsewhere, or reading anything else is still refused:
kubectl auth can-i delete pods -n k8s-from-zero --as=system:serviceaccount:k8s-from-zero:inspector
kubectl auth can-i list pods -n kube-system --as=system:serviceaccount:k8s-from-zero:inspector
kubectl auth can-i list services -n k8s-from-zero --as=system:serviceaccount:k8s-from-zero:inspector
kubectl auth can-i list nodes --as=system:serviceaccount:k8s-from-zero:inspectorExplain this command
kubectl auth can-i delete pods -n k8s-from-zero --as=system:serviceaccount:k8s-from-zero:inspector
kubectl auth can-i list pods -n kube-system --as=system:serviceaccount:k8s-from-zero:inspector
kubectl auth can-i list services -n k8s-from-zero --as=system:serviceaccount:k8s-from-zero:inspector
kubectl auth can-i list nodes --as=system:serviceaccount:k8s-from-zero:inspectorkubectlThe Kubernetes command-line client. Subcommands and flags are documented under kubernetes.io/docs/reference/kubectl/.authThe command group for authorization and identity checks. It includes can-i and whoami.can-iCheck whether an action is allowed. The docs say kubectl auth can-i VERB [TYPE | TYPE/NAME | NONRESOURCEURL].deleteThe verb to check: may the subject delete objects of this type?podsThe resource type.-nShort form of --namespace. If present, the namespace scope for this CLI request.k8s-from-zeroThe namespace name.--as=system:serviceaccount:k8s-from-zero:inspectorThe subject to impersonate, written as a service account: system:serviceaccount:NAMESPACE:NAME.
Explain this command
kubectl auth can-i delete pods -n k8s-from-zero --as=system:serviceaccount:k8s-from-zero:inspector
kubectl auth can-i list pods -n kube-system --as=system:serviceaccount:k8s-from-zero:inspector
kubectl auth can-i list services -n k8s-from-zero --as=system:serviceaccount:k8s-from-zero:inspector
kubectl auth can-i list nodes --as=system:serviceaccount:k8s-from-zero:inspectorkubectlThe Kubernetes command-line client. Subcommands and flags are documented under kubernetes.io/docs/reference/kubectl/.authThe command group for authorization and identity checks. It includes can-i and whoami.can-iCheck whether an action is allowed. The docs say kubectl auth can-i VERB [TYPE | TYPE/NAME | NONRESOURCEURL].listThe verb to check: may the subject list objects of this type?podsThe resource type.-nShort form of --namespace. If present, the namespace scope for this CLI request.kube-systemThe namespace name.--as=system:serviceaccount:k8s-from-zero:inspectorThe subject to impersonate, written as a service account: system:serviceaccount:NAMESPACE:NAME.
Explain this command
kubectl auth can-i delete pods -n k8s-from-zero --as=system:serviceaccount:k8s-from-zero:inspector
kubectl auth can-i list pods -n kube-system --as=system:serviceaccount:k8s-from-zero:inspector
kubectl auth can-i list services -n k8s-from-zero --as=system:serviceaccount:k8s-from-zero:inspector
kubectl auth can-i list nodes --as=system:serviceaccount:k8s-from-zero:inspectorkubectlThe Kubernetes command-line client. Subcommands and flags are documented under kubernetes.io/docs/reference/kubectl/.authThe command group for authorization and identity checks. It includes can-i and whoami.can-iCheck whether an action is allowed. The docs say kubectl auth can-i VERB [TYPE | TYPE/NAME | NONRESOURCEURL].listThe verb to check: may the subject list objects of this type?servicesThe resource type.-nShort form of --namespace. If present, the namespace scope for this CLI request.k8s-from-zeroThe namespace name.--as=system:serviceaccount:k8s-from-zero:inspectorThe subject to impersonate, written as a service account: system:serviceaccount:NAMESPACE:NAME.
Explain this command
kubectl auth can-i delete pods -n k8s-from-zero --as=system:serviceaccount:k8s-from-zero:inspector
kubectl auth can-i list pods -n kube-system --as=system:serviceaccount:k8s-from-zero:inspector
kubectl auth can-i list services -n k8s-from-zero --as=system:serviceaccount:k8s-from-zero:inspector
kubectl auth can-i list nodes --as=system:serviceaccount:k8s-from-zero:inspectorkubectlThe Kubernetes command-line client. Subcommands and flags are documented under kubernetes.io/docs/reference/kubectl/.authThe command group for authorization and identity checks. It includes can-i and whoami.can-iCheck whether an action is allowed. The docs say kubectl auth can-i VERB [TYPE | TYPE/NAME | NONRESOURCEURL].listThe verb to check: may the subject list objects of this type?nodesThe resource type.--as=system:serviceaccount:k8s-from-zero:inspectorThe subject to impersonate, written as a service account: system:serviceaccount:NAMESPACE:NAME.
no
no
no
Warning: resource 'nodes' is not namespace scoped
no
- Reuse a built-in ClusterRole in one namespace. Save this as
view-in-namespace.yaml:
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: inspector-views
namespace: k8s-from-zero
subjects:
- kind: ServiceAccount
name: inspector
namespace: k8s-from-zero
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole # a built-in ClusterRole, granted only in this namespace
name: view
kubectl apply -f view-in-namespace.yaml
kubectl auth can-i list services -n k8s-from-zero --as=system:serviceaccount:k8s-from-zero:inspector
kubectl auth can-i list services -n kube-system --as=system:serviceaccount:k8s-from-zero:inspector
kubectl auth can-i get secrets -n k8s-from-zero --as=system:serviceaccount:k8s-from-zero:inspectorExplain this command
kubectl apply -f view-in-namespace.yaml
kubectl auth can-i list services -n k8s-from-zero --as=system:serviceaccount:k8s-from-zero:inspector
kubectl auth can-i list services -n kube-system --as=system:serviceaccount:k8s-from-zero:inspector
kubectl auth can-i get secrets -n k8s-from-zero --as=system:serviceaccount:k8s-from-zero:inspectorkubectlThe Kubernetes command-line client. Subcommands and flags are documented under kubernetes.io/docs/reference/kubectl/.applyApply a configuration to a resource by file name or stdin. The apply docs say the resource is created if it does not exist yet. JSON and YAML are accepted.-fShort form of --filename. The file, directory or URL that contains the configuration to apply.view-in-namespace.yamlThe file named by --filename. apply creates the objects or updates them to match this file.
Explain this command
kubectl apply -f view-in-namespace.yaml
kubectl auth can-i list services -n k8s-from-zero --as=system:serviceaccount:k8s-from-zero:inspector
kubectl auth can-i list services -n kube-system --as=system:serviceaccount:k8s-from-zero:inspector
kubectl auth can-i get secrets -n k8s-from-zero --as=system:serviceaccount:k8s-from-zero:inspectorkubectlThe Kubernetes command-line client. Subcommands and flags are documented under kubernetes.io/docs/reference/kubectl/.authThe command group for authorization and identity checks. It includes can-i and whoami.can-iCheck whether an action is allowed. The docs say kubectl auth can-i VERB [TYPE | TYPE/NAME | NONRESOURCEURL].listThe verb to check: may the subject list objects of this type?servicesThe resource type.-nShort form of --namespace. If present, the namespace scope for this CLI request.k8s-from-zeroThe namespace name.--as=system:serviceaccount:k8s-from-zero:inspectorThe subject to impersonate, written as a service account: system:serviceaccount:NAMESPACE:NAME.
Explain this command
kubectl apply -f view-in-namespace.yaml
kubectl auth can-i list services -n k8s-from-zero --as=system:serviceaccount:k8s-from-zero:inspector
kubectl auth can-i list services -n kube-system --as=system:serviceaccount:k8s-from-zero:inspector
kubectl auth can-i get secrets -n k8s-from-zero --as=system:serviceaccount:k8s-from-zero:inspectorkubectlThe Kubernetes command-line client. Subcommands and flags are documented under kubernetes.io/docs/reference/kubectl/.authThe command group for authorization and identity checks. It includes can-i and whoami.can-iCheck whether an action is allowed. The docs say kubectl auth can-i VERB [TYPE | TYPE/NAME | NONRESOURCEURL].listThe verb to check: may the subject list objects of this type?servicesThe resource type.-nShort form of --namespace. If present, the namespace scope for this CLI request.kube-systemThe namespace name.--as=system:serviceaccount:k8s-from-zero:inspectorThe subject to impersonate, written as a service account: system:serviceaccount:NAMESPACE:NAME.
Explain this command
kubectl apply -f view-in-namespace.yaml
kubectl auth can-i list services -n k8s-from-zero --as=system:serviceaccount:k8s-from-zero:inspector
kubectl auth can-i list services -n kube-system --as=system:serviceaccount:k8s-from-zero:inspector
kubectl auth can-i get secrets -n k8s-from-zero --as=system:serviceaccount:k8s-from-zero:inspectorkubectlThe Kubernetes command-line client. Subcommands and flags are documented under kubernetes.io/docs/reference/kubectl/.authThe command group for authorization and identity checks. It includes can-i and whoami.can-iCheck whether an action is allowed. The docs say kubectl auth can-i VERB [TYPE | TYPE/NAME | NONRESOURCEURL].getThe verb to check: may the subject read single objects of this type?secretsThe resource type.-nShort form of --namespace. If present, the namespace scope for this CLI request.k8s-from-zeroThe namespace name.--as=system:serviceaccount:k8s-from-zero:inspectorThe subject to impersonate, written as a service account: system:serviceaccount:NAMESPACE:NAME.
rolebinding.rbac.authorization.k8s.io/inspector-views created
yes
no
no
Services are readable here and not in kube-system, and Secrets stay hidden, as the view role promises.
- Grant a cluster-scoped permission. Nodes do not belong to any namespace, so only a ClusterRole with a ClusterRoleBinding can grant them. Save this as
node-reader.yaml:
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: node-reader
rules:
- apiGroups: [""]
resources: ["nodes"]
verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: inspector-reads-nodes
subjects:
- kind: ServiceAccount
name: inspector
namespace: k8s-from-zero
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: node-reader
kubectl apply -f node-reader.yaml
kubectl auth can-i list nodes --as=system:serviceaccount:k8s-from-zero:inspectorExplain this command
kubectl apply -f node-reader.yaml
kubectl auth can-i list nodes --as=system:serviceaccount:k8s-from-zero:inspectorkubectlThe Kubernetes command-line client. Subcommands and flags are documented under kubernetes.io/docs/reference/kubectl/.applyApply a configuration to a resource by file name or stdin. The apply docs say the resource is created if it does not exist yet. JSON and YAML are accepted.-fShort form of --filename. The file, directory or URL that contains the configuration to apply.node-reader.yamlThe file named by --filename. apply creates the objects or updates them to match this file.
Explain this command
kubectl apply -f node-reader.yaml
kubectl auth can-i list nodes --as=system:serviceaccount:k8s-from-zero:inspectorkubectlThe Kubernetes command-line client. Subcommands and flags are documented under kubernetes.io/docs/reference/kubectl/.authThe command group for authorization and identity checks. It includes can-i and whoami.can-iCheck whether an action is allowed. The docs say kubectl auth can-i VERB [TYPE | TYPE/NAME | NONRESOURCEURL].listThe verb to check: may the subject list objects of this type?nodesThe resource type.--as=system:serviceaccount:k8s-from-zero:inspectorThe subject to impersonate, written as a service account: system:serviceaccount:NAMESPACE:NAME.
clusterrole.rbac.authorization.k8s.io/node-reader created
clusterrolebinding.rbac.authorization.k8s.io/inspector-reads-nodes created
Warning: resource 'nodes' is not namespace scoped
yes
To see everything a subject may do in a namespace, list it:
kubectl auth can-i --list -n k8s-from-zero --as=system:serviceaccount:k8s-from-zero:inspectorExplain this command
kubectl auth can-i --list -n k8s-from-zero --as=system:serviceaccount:k8s-from-zero:inspectorkubectlThe Kubernetes command-line client. Subcommands and flags are documented under kubernetes.io/docs/reference/kubectl/.authThe command group for authorization and identity checks. It includes can-i and whoami.can-iCheck whether an action is allowed. The docs say kubectl auth can-i VERB [TYPE | TYPE/NAME | NONRESOURCEURL].--listWith auth can-i, print every action the subject is allowed, instead of checking one verb.-nShort form of --namespace. If present, the namespace scope for this CLI request.k8s-from-zeroThe namespace name.--as=system:serviceaccount:k8s-from-zero:inspectorThe subject to impersonate, written as a service account: system:serviceaccount:NAMESPACE:NAME.
Resources Non-Resource URLs Resource Names Verbs
selfsubjectreviews.authentication.k8s.io [] [] [create]
selfsubjectaccessreviews.authorization.k8s.io [] [] [create]
selfsubjectrulesreviews.authorization.k8s.io [] [] [create]
bindings [] [] [get list watch]
configmaps [] [] [get list watch]
...
nodes [] [] [get list watch]
...
pods [] [] [get list watch]
...
services [] [] [get list watch]
...
- Look inside the tokens. A JWT has three parts separated by dots; the middle part is base64-encoded JSON.
kubectl create tokenasks the TokenRequest API for a short-lived token you can use from outside the cluster:
kubectl create token inspector -n k8s-from-zero --duration=10m | cut -d. -f2 | base64 -d 2>/dev/null; echoExplain this command
kubectl create token inspector -n k8s-from-zero --duration=10m | cut -d. -f2 | base64 -d 2>/dev/null; echokubectlThe Kubernetes command-line client. Subcommands and flags are documented under kubernetes.io/docs/reference/kubectl/.createCreate a resource from a file or from stdin. Here it takes the subcommand that follows.tokenThe create subcommand: kubectl create token requests a token for the ServiceAccount named next.inspectorThe object name.-nShort form of --namespace. If present, the namespace scope for this CLI request.k8s-from-zeroThe namespace name.--duration=10mHow long the issued token should be valid. This command passes 10m.|A shell pipe. The output of the command on the left becomes the input of the command on the right.cutShell. Cut out selected fields from each line.-d.With cut, split each line at dots. A JWT has three dot-separated parts.-f2With cut, keep the second field: the JWT payload.|A shell pipe. The output of the command on the left becomes the input of the command on the right.base64Encode or decode base64 data. The lesson uses -d to decode a JWT payload.-dWith base64, decode the input.2>/dev/nullA shell redirect. It discards base64's error message: JWT parts drop the base64 padding, so base64 -d can report invalid input at the end even though the JSON prints.
Explain this command
kubectl create token inspector -n k8s-from-zero --duration=10m | cut -d. -f2 | base64 -d 2>/dev/null; echoechoPrint a newline, because the decoded payload does not end with one.
{"aud":["https://kubernetes.default.svc.cluster.local"],"exp":1794346654,"iat":1794346054,"iss":"https://kubernetes.default.svc.cluster.local","jti":"1bf4f958-5e0e-4767-afa3-708ee7a91b5d","kubernetes.io":{"namespace":"k8s-from-zero","serviceaccount":{"name":"inspector","uid":"a2d5ea4d-a171-4964-babd-e17f58acfd3c"}},"nbf":1794346054,"sub":"system:serviceaccount:k8s-from-zero:inspector"}
exp minus iat is 600 seconds, the 10 minutes you asked for. (base64 -d may complain about missing padding; 2>/dev/null hides that.) Now the token the kubelet mounted in the Pod:
kubectl exec -n k8s-from-zero inspector -- sh -c 'cut -d. -f2 /var/run/secrets/kubernetes.io/serviceaccount/token | base64 -d 2>/dev/null; echo'Explain this command
kubectl exec -n k8s-from-zero inspector -- sh -c 'cut -d. -f2 /var/run/secrets/kubernetes.io/serviceaccount/token | base64 -d 2>/dev/null; echo'kubectlThe Kubernetes command-line client. Subcommands and flags are documented under kubernetes.io/docs/reference/kubectl/.execExecute a command in a container. The synopsis is kubectl exec (POD | TYPE/NAME) [-c CONTAINER] [flags] -- COMMAND [args...].-nShort form of --namespace. If present, the namespace scope for this CLI request.k8s-from-zeroThe namespace name.inspectorThe object name.--Ends kubectl's flags. The exec examples say to use two dashes so the command's own flags are read as that command's flags.shA shell. The command that follows runs inside it.-cAn argument of sh. It tells sh to run the command string that follows.'cut -d. -f2 /var/run/secrets/kubernetes.io/serviceaccount/token | base64 -d 2>/dev/null; echo'The command string sh runs inside the container: cut the payload out of the mounted token, decode it, and end with a newline.
{"aud":["https://kubernetes.default.svc.cluster.local"],"exp":1825882023,"iat":1794346023,"iss":"https://kubernetes.default.svc.cluster.local","jti":"f9c21ca6-0bfb-44bb-8711-3216a53aebcb","kubernetes.io":{"namespace":"k8s-from-zero","node":{"name":"k8s-ep19-control-plane","uid":"0359fb81-13ac-4ee9-8cfd-edc402b0fd22"},"pod":{"name":"inspector","uid":"9d2325a0-a32a-4d5a-ac62-9b52bb35991a"},"serviceaccount":{"name":"inspector","uid":"a2d5ea4d-a171-4964-babd-e17f58acfd3c"},"warnafter":1794349630},"nbf":1794346023,"sub":"system:serviceaccount:k8s-from-zero:inspector
This one names the Pod and the node it is bound to. Its exp is a year after iat, which looks wrong for a short-lived token. The explanation is warnafter: 3,607 seconds after iat, matching the expirationSeconds: 3607 in the Pod’s projected volume. The API server flag --service-account-extend-token-expiration (default true) extends tokens injected by admission up to one year, so that old clients that never reload the file keep working during the move from legacy tokens; warnafter marks where the real one-hour lifetime ends (kube-apiserver reference, Managing Service Accounts). Your app should still reload the token file regularly; the docs say loading it on a schedule, for example once every 5 minutes, is often good enough (Configure Service Accounts for Pods). (The last characters of the output are cut off because the unpadded base64 ends early; the claims you need are all there.)
- Turn the token off where it is not needed. Save this as
no-token.yaml:
apiVersion: v1
kind: Pod
metadata:
name: no-token
namespace: k8s-from-zero
spec:
automountServiceAccountToken: false
containers:
- name: app
image: busybox:1.37
command: ["sleep", "3600"]
kubectl apply -f no-token.yaml
kubectl exec -n k8s-from-zero no-token -- ls /var/run/secrets/kubernetes.io/serviceaccount
kubectl get pod no-token -n k8s-from-zero -o jsonpath='{.spec.serviceAccountName}{"\n"}'Explain this command
kubectl apply -f no-token.yaml
kubectl exec -n k8s-from-zero no-token -- ls /var/run/secrets/kubernetes.io/serviceaccount
kubectl get pod no-token -n k8s-from-zero -o jsonpath='{.spec.serviceAccountName}{"\n"}'kubectlThe Kubernetes command-line client. Subcommands and flags are documented under kubernetes.io/docs/reference/kubectl/.applyApply a configuration to a resource by file name or stdin. The apply docs say the resource is created if it does not exist yet. JSON and YAML are accepted.-fShort form of --filename. The file, directory or URL that contains the configuration to apply.no-token.yamlThe file named by --filename. apply creates the objects or updates them to match this file.
Explain this command
kubectl apply -f no-token.yaml
kubectl exec -n k8s-from-zero no-token -- ls /var/run/secrets/kubernetes.io/serviceaccount
kubectl get pod no-token -n k8s-from-zero -o jsonpath='{.spec.serviceAccountName}{"\n"}'kubectlThe Kubernetes command-line client. Subcommands and flags are documented under kubernetes.io/docs/reference/kubectl/.execExecute a command in a container. The synopsis is kubectl exec (POD | TYPE/NAME) [-c CONTAINER] [flags] -- COMMAND [args...].-nShort form of --namespace. If present, the namespace scope for this CLI request.k8s-from-zeroThe namespace name.no-tokenThe object name.--Ends kubectl's flags. The exec examples say to use two dashes so the command's own flags are read as that command's flags.lsList the files in a directory. It runs inside the container./var/run/secrets/kubernetes.io/serviceaccountThe directory where Kubernetes mounts the Pod's ServiceAccount files: token, ca.crt and namespace.
Explain this command
kubectl apply -f no-token.yaml
kubectl exec -n k8s-from-zero no-token -- ls /var/run/secrets/kubernetes.io/serviceaccount
kubectl get pod no-token -n k8s-from-zero -o jsonpath='{.spec.serviceAccountName}{"\n"}'kubectlThe Kubernetes command-line client. Subcommands and flags are documented under kubernetes.io/docs/reference/kubectl/.getDisplay one or many resources. kubectl get prints a table of the most important information about the resources you name.podThe resource type to display. kubectl get points you to kubectl api-resources for the full list of types the server supports.no-tokenThe object name.-nShort form of --namespace. If present, the namespace scope for this CLI request.k8s-from-zeroThe namespace name.-oShort form of --output. It selects the output format. For get, the formats include json, yaml, name, jsonpath, custom-columns and wide.jsonpath='{.spec.serviceAccountName}{"\n"}'A jsonpath output format. The get docs say jsonpath prints the fields the expression selects. The lesson uses this path to print the fields named in the command.
pod/no-token created
ls: /var/run/secrets/kubernetes.io/serviceaccount: No such file or directory
command terminated with exit code 1
default
The Pod still runs as the default ServiceAccount, but it has no credential to prove it.
- Clean up:
kubectl delete -f no-token.yaml -f view-in-namespace.yaml -f node-reader.yaml -f pod-reader.yaml -f inspector.yamlExplain this command
kubectl delete -f no-token.yaml -f view-in-namespace.yaml -f node-reader.yaml -f pod-reader.yaml -f inspector.yamlkubectlThe Kubernetes command-line client. Subcommands and flags are documented under kubernetes.io/docs/reference/kubectl/.deleteDelete resources by file names, stdin, resources and names, or by resources and label selector.-fShort form of --filename. For delete, the file that contains the resource to delete.no-token.yamlThe file named by --filename. delete removes the resources that file describes.-fShort form of --filename. For delete, the file that contains the resource to delete.view-in-namespace.yamlThe file named by --filename. delete removes the resources that file describes.-fShort form of --filename. For delete, the file that contains the resource to delete.node-reader.yamlThe file named by --filename. delete removes the resources that file describes.-fShort form of --filename. For delete, the file that contains the resource to delete.pod-reader.yamlThe file named by --filename. delete removes the resources that file describes.-fShort form of --filename. For delete, the file that contains the resource to delete.inspector.yamlThe file named by --filename. delete removes the resources that file describes.
When it goes wrong
- A Role looks right but
can-isays no. CheckapiGroups. We wrote a Role fordeploymentswithapiGroups: [""]and bound it to a ServiceAccounthelper;kubectl auth can-i list deploymentsansweredno.kubectl api-resourcesshows where a resource lives:
NAME SHORTNAMES APIVERSION NAMESPACED KIND
deployments deploy apps/v1 true Deployment
apps/v1 means the group is apps. After patching the rule to apiGroups: ["apps"] the same check answered yes.
- You cannot point a binding at another role. Changing
roleReffails:
The RoleBinding "helper-reads-deployments" is invalid: roleRef: Invalid value: {"APIGroup":"rbac.authorization.k8s.io","Kind":"Role","Name":"pod-reader"}: field is immutable
Delete the binding and create a new one. The docs explain why: this way, permission to update a binding does not quietly become permission to grant any role.
-
The binding exists, the subject still has no access. A ServiceAccount subject needs the namespace of the ServiceAccount, which is not always the binding’s namespace. We ran
kubectl create rolebinding helper-wrong-ns -n k8s-from-zero --role=pod-reader --serviceaccount=default:helper. The binding was created, but it grants a ServiceAccounthelperin the namespacedefault, and ours lives ink8s-from-zero, socan-istayed atno.kubectl get rolebinding -o wideshows the subject asdefault/helper, which gives it away. -
An app logs 403 Forbidden. Read the message as the RBAC sentence, as in step 3, then reproduce it with
kubectl auth can-i <verb> <resource> -n <namespace> --as=system:serviceaccount:NAMESPACE:NAME. Grant the missing verb and resource with the smallest Role that works. The RBAC good practices page lists what to avoid, such as wildcard rules and grantingcluster-adminto workloads.
Cheat sheet
| Task | Command or field | Note |
|---|---|---|
| Who am I | kubectl auth whoami |
add --as=... to check another subject |
| Can I do it | kubectl auth can-i list pods -n NS |
answers yes or no |
| Can a ServiceAccount do it | kubectl auth can-i VERB RES -n NS --as=system:serviceaccount:NS:NAME |
needs impersonate permission |
| Everything a subject may do | kubectl auth can-i --list -n NS --as=... |
per namespace |
| Create a ServiceAccount | kubectl create serviceaccount NAME -n NS |
one per app |
| Use it in a Pod | spec.serviceAccountName: NAME |
default is default |
| No token in the Pod | automountServiceAccountToken: false |
Pod setting beats ServiceAccount |
| Generate a Role | kubectl create role NAME --verb=get,list --resource=pods --dry-run=client -o yaml |
namespaced |
| Generate a RoleBinding | kubectl create rolebinding NAME --role=R --serviceaccount=NS:SA |
or --clusterrole=view |
| Cluster-wide grant | ClusterRole + ClusterRoleBinding | needed for nodes |
| Find a resource’s API group | kubectl api-resources |
apps/v1 means group apps |
| Short-lived token | kubectl create token SA -n NS --duration=10m |
TokenRequest API |
| Token files in a Pod | /var/run/secrets/kubernetes.io/serviceaccount/ |
token, ca.crt, namespace |
| Change a binding’s role | delete and recreate | roleRef is immutable |
Minimal Role and RoleBinding:
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: pod-reader
namespace: k8s-from-zero
rules:
- apiGroups: [""]
resources: ["pods"]
verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: inspector-reads-pods
namespace: k8s-from-zero
subjects:
- kind: ServiceAccount
name: inspector
namespace: k8s-from-zero
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: pod-reader
Recap and what is next
- Each API request is authenticated (who) and then authorized by RBAC (may they). Permissions only add up; there are no deny rules.
- Roles and ClusterRoles hold rules; RoleBindings grant them in one namespace, ClusterRoleBindings everywhere. A ClusterRole plus a RoleBinding is how you reuse
view,editandadminper namespace. - A ServiceAccount is a Pod’s identity. Its token is mounted by the kubelet, bound to the Pod, and rotated; turn it off with
automountServiceAccountToken: falsewhen the app does not call the API. - Read a 403 message as who, what, which, where, and reproduce it with
kubectl auth can-i --as.
Command explanations and quoted passages in this lesson come from or adapt the kubectl reference and the Kubernetes documentation, © The Kubernetes Authors, licensed under CC BY 4.0. We shortened and edited some passages. Kubernetes® is a registered trademark of The Linux Foundation. aitamer.news is not affiliated with or endorsed by The Linux Foundation or the CNCF.

The Campfire
CommentsThanks. Your comment is waiting for the desk. Once it is approved it appears here within about a minute.
Add a comment