如何查看K8s中特定ServiceAccount关联的权限与角色?
Hey there! When you run kubectl get sa default, you only get surface-level metadata about the ServiceAccount. To uncover the actual permissions and roles tied to a specific ServiceAccount, we need to work through Kubernetes' role binding system. Here's a clear breakdown of the commands you'll need:
RoleBindings grant namespace-specific permissions to a ServiceAccount. Use this command to list bindings for your target SA (replace <namespace> and <sa-name> with your values):
kubectl get rolebindings -n <namespace> --field-selector subject.kind=ServiceAccount,subject.name=<sa-name>
For your default SA in the default namespace, that would be:
kubectl get rolebindings -n default --field-selector subject.kind=ServiceAccount,subject.name=default
The output will show you which Roles are bound to the SA in this namespace.
ClusterRoleBindings grant cluster-wide permissions. Use this command to check for cluster-level bindings (note we include the namespace since ServiceAccounts are namespace-scoped):
kubectl get clusterrolebindings --field-selector subject.kind=ServiceAccount,subject.name=<sa-name>,subject.namespace=<namespace>
Again, for the default SA in default namespace:
kubectl get clusterrolebindings --field-selector subject.kind=ServiceAccount,subject.name=default,subject.namespace=default
Once you have the name of a Role or ClusterRole from the above steps, you can dig into its specific permissions.
For a namespace-scoped Role:
To get a human-readable description:
kubectl describe role <role-name> -n <namespace>
Or to see the full YAML definition (great for precise details):
kubectl get role <role-name> -n <namespace> -o yaml
For a cluster-scoped ClusterRole:
Human-readable description:
kubectl describe clusterrole <clusterrole-name>
Full YAML definition:
kubectl get clusterrole <clusterrole-name> -o yaml
If you want a consolidated view of all bindings for your SA, you can use jq (a JSON processor) to parse the output:
# Check namespace-level bindings kubectl get rolebindings -n default --field-selector subject.kind=ServiceAccount,subject.name=default -o json | jq '.items[] | {binding_name: .metadata.name, role: .roleRef.name, role_kind: .roleRef.kind}' # Check cluster-level bindings kubectl get clusterrolebindings --field-selector subject.kind=ServiceAccount,subject.name=default,subject.namespace=default -o json | jq '.items[] | {binding_name: .metadata.name, role: .roleRef.name, role_kind: .roleRef.kind}'
This will list all bindings along with the associated role names, which you can then inspect using the commands above.
A quick note: If you don't see any bindings returned, that means the ServiceAccount only has the default, minimal permissions granted to all unbound SAs in Kubernetes.
内容的提问来源于stack exchange,提问作者injoy

