How to create a service account to get a list of pods from inside a Kubernetes cluster?

7/14/2020

I have created a service account to get a list of pods in minikube.

apiVersion: v1
kind: ServiceAccount
metadata:
  name: demo-sa
---
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: Role
metadata:
  name: list-pods
  namespace: default
rules:
  - apiGroups:
    - ''
    resources:
      - pods
    verbs:
      - list
---
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: RoleBinding
metadata:
 name: list-pods_demo-sa
 namespace: default
roleRef:
 kind: Role
 name: list-pods
 apiGroup: rbac.authorization.k8s.io
subjects:
  - kind: ServiceAccount
    name: demo-sa
    namespace: default

The problem is, that I get an error message if I use the service account to get the list of pods. kubectl auth can-i list pod --as demo-sa answers always with no.

-- user3389757
kubernetes

1 Answer

7/14/2020

You cannot use:

kubectl auth can-i list pod --as <something>

to impersonate ServiceAccounts. You can only impersonate users --as and impersonate groups --as-group

A workaround is to use the service account token.

kubectl get secret demo-sa-token-7fx44 -o=jsonpath='{.data.token}' | base64 -d

You can use the output here and any kubectl request. However, I checked with kubectl auth can-i list pod and I don't think auth works with a token (you always get a yes)

-- Rico
Source: StackOverflow