使用Kubernetes Python API访问Pod时遇401/403权限问题求助
问题描述
我尝试用Kubernetes Python客户端访问集群资源,但无法正常工作。虽然已经配置并应用了清单,但还是无法列出Pod。用kubectl验证权限显示该服务账号拥有list pods权限:
$ kubectl auth can-i list pods --as=system:serviceaccount:default:my-service-account yes
我的Python代码如下:
import kubernetes as k8s from kubernetes.client.api.core_api import ApiClient from kubernetes import client, config service_account_name = "my-service-account" SA_TOKEN = "the-token" # Configure API key authorization: BearerToken configuration = k8s.client.Configuration( host="https://192.168.49.2:8443", api_key={"authorization": SA_TOKEN}, api_key_prefix={"authorization": "Bearer"}, username=service_account_name, discard_unknown_keys=True ) configuration.verify_ssl = False configuration.client_side_validation = False api_client = k8s.client.ApiClient(configuration=configuration) v1 = k8s.client.CoreV1Api(api_client) v1.list_namespaced_pod("default")
执行后输出错误:
ApiException: (401) Reason: Unauthorized HTTP response headers: HTTPHeaderDict({'Audit-Id': 'c0ec14f1-80fb-4177-b719-273c76230f6c', 'Cache-Control': 'no-cache, private', 'Content-Type': 'application/json', 'Date': 'Thu, 24 Aug 2023 09:00:59 GMT', 'Content-Length': '129'}) HTTP response body: {"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"Unauthorized","reason":"Unauthorized","code":401}
手动执行curl请求也得到类似结果:
$ curl --cert ~/.minikube/ca.crt --key ~/.minikube/ca.key -k \ -H "Authorization: Bearer $(kubectl get secret my-secret -o jsonpath='{.data.token}')" \ https://192.168.49.2:8443/api/v1/namespaces/default/pods { "kind": "Status", "apiVersion": "v1", "metadata": {}, "status": "Failure", "message": "pods is forbidden: User \"minikubeCA\" cannot list resource \"pods\" in API group \"\" in the namespace \"default\"", "reason": "Forbidden", "details": { "kind": "pods" }, "code": 403 }
Kubernetes清单
以下是我应用到集群的清单:
--- apiVersion: v1 kind: ServiceAccount metadata: name: my-service-account namespace: default secrets: - name: my-secret --- apiVersion: v1 kind: Secret metadata: name: my-secret namespace: default annotations: kubernetes.io/service-account.name: my-service-account type: kubernetes.io/service-account-token --- apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: namespace: default name: reader-role rules: - apiGroups: [""] # Empty string ("") indicates core API group resources: ["pods", "pods/logs"] verbs: ["get", "watch", "list"] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: name: reader-binding namespace: default roleRef: apiGroup: rbac.authorization.k8s.io kind: Role name: reader-role subjects: - kind: ServiceAccount name: my-service-account namespace: default
内容的提问来源于stack exchange,提问作者Stefan Falk
相关产品推荐
相关产品推荐

