python client通过token连接k8sAPI cluster

1、创建一个k8s admin-user

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
kubectl apply -f - <<EOF
---

#在kube-system下创建admin-user
apiVersion: v1
kind: ServiceAccount
metadata:
name: admin-user
namespace: kube-system
---

#给admin-user cluster-admin权限
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRoleBinding
metadata:
name: admin-user
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: cluster-admin
subjects:
- kind: ServiceAccount
name: admin-user
namespace: kube-system
EOF

查看k8sCluster APIURL地址

1
kubectl config view --minify | grep server | cut -f 2- -d ":" | tr -d " "

获取刚刚创建的admin-user token在把base64解密出来的token

1
kubectl -n kube-system   get secrets admin-user-token-dpg67   -o go-template --template '{{index .data "token"}}' | base64 -d

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from kubernetes import client, config

#see https://kubernetes.io/docs/tasks/administer-cluster/access-cluster-api/#accessing-the-cluster-api to know how to get the token
#The command look like kubectl get secrets | grep default | cut -f1 -d ' ') | grep -E '^token' | cut -f2 -d':' | tr -d '\t' but better check the official doc link
aToken="eyJhbGciOiJSUzI1NiIsImtpZCI6IiJ9.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJrdWJlLXN5c3RlbSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VjcmV0Lm5hbWUiOiJhZG1pbi11c2VyLXRva2VuLXhsZnF3Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQubmFtZSI6ImFkbWluLXVzZXIiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC51aWQiOiI5MmEzN2JkNi1hYjg5LTExZTktODkyMi0wODAwMjdlMWY4NDYiLCJzdWIiOiJzeXN0ZW06c2VydmljZWFjY291bnQ6a3ViZS1zeXN0ZW06YWRtaW4tdXNlciJ9.GRerIItaGUf8PV8rb3eDsmP90YZCd3BGWuYhXr_y2f4zmd59rpHfP8E6xWoHQiav84Kq1b9E8tiEHC9aoPcNmmclS8AIm95DA-QHv_5WJrJPcTB-XpzF1ccPFSdJQ0hmjw54pxQo4gQLJ1MouPiwH-sWjVM1OYiEmillvglIiFfTrc24fJj1Fu2V46lsUXLPKBVrny3v6soUjteU4IDJxjHhQodpFSBbxnYVUvaK_hvthDv_IsCcY2rQ16ii4n6tTt8vf1D0NKZv4pWeXH2sRhzQ5Q3aK8VjZAd6PBd3iVMz2Gp24KWqFoqQ9-TRgwL6oIoHT3E0qEoapDzxg9jWSA"


# Configs can be set in Configuration class directly or using helper utility
configuration = client.Configuration()
configuration.host="https://192.168.99.100:8443"
configuration.verify_ssl=False
configuration.debug = True

#Maybe there is a way to use these options instead of token since they are provided in Google cloud UI
#configuration.username = "admin"
#configuration.password = "XXXXXXXXXXX"
configuration.api_key={"authorization":"Bearer "+ aToken}
client.Configuration.set_default(configuration)

v1 = client.CoreV1Api()
print("Listing pods with their IPs:")
ret = v1.list_pod_for_all_namespaces(watch=False)
for i in ret.items:
trueprint("%s\t%s\t%s" % (i.status.pod_ip, i.metadata.namespace, i.metadata.name))