Ramdas Nair:
Hello. I would like to know why the command kubectl get pods --as kubernetes-admin is not allowed int the default namespace of a cluster created by kubeadm? I get the error: Error from server (Forbidden): pods is forbidden: User “kubernetes-admin” cannot list resource “pods” in API group “” in the namespace “default”. The user exists in the kubeconfig file however:
apiVersion: v1
clusters:
- cluster:
certificate-authority-data: DATA+OMITTED
server: https://controlplane:6443
name: kubernetes
contexts:
- context:
cluster: kubernetes
user: kubernetes-admin
name: kubernetes-admin@kubernetes
current-context: kubernetes-admin@kubernetes
kind: Config
preferences: {}
users:
- name: dev-user
user:
client-certificate-data: DATA+OMITTED
client-key-data: DATA+OMITTED
- name: kubernetes-admin
user:
client-certificate-data: DATA+OMITTED
client-key-data: DATA+OMITTED
Santosh Kaluskar:
Have you tried kubectl auth can-i get pods —as kubernetes-admin?
Alistair Mackay:
Now I don’t exacly know why, but it appears you need to specify the user’s group as well if the user has one, and for kubernetes-admin, this is system::masters
kubectl get pods --as-group=system:masters --as kubernetes-admin
How do we find the group?
cat .kube/config | yq e '.users[1].user.client-certificate-data' | base64 -d > kubernetes-admin.crt
openssl x509 -in kubernetes-admin.crt -noout -text
If you don’t have yq
on your environment, either install it, or copy the text of client-certificate-data
and paste to
echo -n "<paste it here>" | base64 -d > kubernetes-admin.crt
The output of openssl yields the group ( as O=
) and user (as CN=
) in the Subject
field
Certificate:
Data:
Version: 3 (0x2)
Serial Number: 6915291762401448068 (0x5ff80d38181f9084)
Signature Algorithm: sha256WithRSAEncryption
Issuer: CN = kubernetes
Validity
Not Before: Aug 15 06:51:24 2022 GMT
Not After : Aug 15 06:51:27 2023 GMT
Subject: O = system:masters, CN = kubernetes-admin
Santosh Kaluskar:
TIL kubectl get
has —as
flag as well.
Alistair Mackay:
--as
and --as-group
are global flags. Means they apply to all kubectl
commands where authentication is required (which is probably 99% of them)
Ramdas Nair:
Thank you @Alistair Mackay, it works after adding the group. @Santosh Kaluskar, same applies to auth
as well.
Santosh Kaluskar:
Thank you!
Alistair Mackay:
In general, you only really need to use --as
if you are the admin by default and want to impersonate a different user - usually for the purpose of testing RBAC changes
Alistair Mackay:
And know that you can use auth
to test service accounts too. You must give the fully qualified SA name,
kubectl auth can-i get pods --as system:serviceaccount:namespace_name:service_account_name