from kubernetes import client, config
configuration = client.Configuration()
configuration.host = "https://192.168.3.21:6443"
configuration.ssl_ca_cert = "ca.pem"
configuration.verify_ssl = True
token = 'eyJhbGciOiJSUzI1NiIsImtpZCI6IkhZWDFDVkxFZmJ6SEExaDhhMDJXdU4wVjlMU2FwcVZaV1RFWFB3SmNNSGsifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJrdWJlLXN5c3RlbSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VjcmV0Lm5hbWUiOiJkYXNoYm9hcmQtYWRtaW4tdG9rZW4tMnRkcHMiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoiZGFzaGJvYXJkLWFkbWluIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiYTM4MDFhMjctYWU0Mi00NjAwLTkwZjUtOTEwMDQ5OTQ3NzA1Iiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50Omt1YmUtc3lzdGVtOmRhc2hib2FyZC1hZG1pbiJ9.kK46HMq8sDqpnQBUHnxwUYhAKJ09eva2RxVvNbfdAaUlDpLd8a9qm2eokUgL2k7IaKUvfxC9G5He9h8JJyvZljrVRd0tlKgO4Cmods1yLjnmnP8hFBQYCVrqMZlAQWL0KwbVrdOhQ3nXVz0lfokUBCqnEdTDbqKfyhNxkm_uQhVAohDrxE-2LUBdYBQDycNRaHPV-rwwP3FDcp8IP1auLq9ZucKa0CY1ynZdJ91a0Rv-FPlmYueeBd51LFxZTmWHml41lOe27gIo7MEXcBPsthpqZvCxQaI7rCbiX3iuDD16kg9PKsxOHnNNiIOk9oXwNL2xayQc3cV79GFFOJ57AA'
configuration.api_key = {"authorization": "Bearer " + token} #注意这里Bearer后面有一个空格,曾经在这里浪费了一晚上时间;另外,authorization这里首字母a是小写的
client.Configuration.set_default(configuration)
v1 = client.CoreV1Api()
ret = v1.list_namespaced_pod('default')
for i in ret.items:
print(i)
# print("%s\t%s\t%s" % (i.status.pod_ip, i.metadata.namespace, i.metadata.name))
报错内容大概是这样子的:
User "system:anonymous" cannot list resource "componentstatuses" in API group
我这里是用python客户端方式访问kubernetes api,通过http检测,排查了一会儿token,发现token没问题:
[root@k8s-master1 ~]# token="xxxxx"
[root@k8s-master1 ~]# curl --cacert /opt/kubernetes/ssl/ca.pem -H "Authorization: Bearer $token" https://192.168.3.21:6443/api/v1/namespaces/default/pods
可以返回json
最后还是问度娘,要给system:anonymous做一个clusterronlebinding,通过如下命令解决:
[root@k8s-master1 ~]# kubectl create clusterrolebinding cluster-system-anonymons --clusterrole=cluster-admin --user=system:anonymous