Python使用Kubernetes API访问集群

时间:2022-09-12 18:27:04

通过将身份认证令牌直接传给 api 服务器,可以避免使用 kubectl 代理,像这样:
使用 grep/cut 方式:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 查看所有的集群,因为你的 .kubeconfig 文件中可能包含多个上下文
kubectl config view -o jsonpath='{"cluster name\tserver\n"}{range .clusters[*]}{.name}{"\t"}{.cluster.server}{"\n"}{end}'
 
# 从上述命令输出中选择你要与之交互的集群的名称
export cluster_name="some_server_name"
 
# 指向引用该集群名称的 api 服务器
apiserver=$(kubectl config view -o jsonpath="{.clusters[?(@.name==\"$cluster_name\")].cluster.server}")
 
# 获得令牌
token=$(kubectl get secrets -o jsonpath="{.items[?(@.metadata.annotations['kubernetes\.io/service-account\.name']=='default')].data.token}"|base64 -d)
 
# 使用令牌玩转 api
curl -x get $apiserver/api --header "authorization: bearer $token" --insecure

客户端库:https://kubernetes.io/zh/docs/reference/using-api/client-libraries/

python举例:

目录结构

Python使用Kubernetes API访问集群

配置文件两种方式

1、将集群中的~/.kube/config,重命名为kubeconfig.yaml
代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from kubernetes import  client,config
from kubernetes.stream import stream
import yaml
config_file = r"d:\users\jackhe\pycharmprojects\jj\k8s\auth\kubeconfig.yaml"
config.kube_config.load_kube_config(config_file=config_file)
api_instance = client.corev1api()
api_batch = client.batchv1api()
 
#列出所有的namesapce
for ns in api_instance.list_namespace().items:
    print(ns.metadata.name)
 
#列出所有的nodes
def list_node():
    api_response = api_instance.list_node()
    data = {}
    for i in api_response.items:
        data[i.metadata.name] = {"name": i.metadata.name,
                                "status": i.status.conditions[-1].type if i.status.conditions[-1].status == "true" else "notready",
                                "ip": i.status.addresses[0].address,
                                "kubelet_version": i.status.node_info.kubelet_version,
                                "os_image": i.status.node_info.os_image,
                                 }
    return data
nodes = list_node()
print(nodes)

2、使用token形式,获取命令上文所示。
代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# -*- coding: utf-8 -*-
from kubernetes.client import api_client
from kubernetes.client.apis import core_v1_api
from kubernetes import client,config
 
 
class kubernetestools(object):
    def __init__(self):
        self.k8s_url = 'https://192.168.1.56:6443'
 
    def get_token(self):
        """
        获取token
        :return:
        """
        with open(r'd:\users\jackhe\pycharmprojects\jj\k8s\auth\token', 'r') as file:
            token = file.read().strip('\n')
            return token
 
    def get_api(self):
        """
        获取api的corev1api版本对象
        :return:
        """
        configuration = client.configuration()
        configuration.host = self.k8s_url
        configuration.verify_ssl = false
        configuration.api_key = {"authorization": "bearer " + self.get_token()}
        client1 = api_client.apiclient(configuration=configuration)
        api = core_v1_api.corev1api(client1)
        return api
 
    def get_namespace_list(self):
        """
        获取命名空间列表
        :return:
        """
        api = self.get_api()
        namespace_list = []
        for ns in api.list_namespace().items:
            # print(ns.metadata.name)
            namespace_list.append(ns.metadata.name)
 
        return namespace_list
 
    def get_pod_list(self):
       api = self.get_api()
       print("listing pods with their ips:")
       ret = api.list_pod_for_all_namespaces(watch=false)
       for i in ret.items:
           print("%s\t%s\t%s" % (i.status.pod_ip, i.metadata.namespace, i.metadata.name))
 
    def get_service_list(self):
        api = self.get_api()
        ret = api.list_service_for_all_namespaces(watch=false)
        for i in ret.items:
            print("%s \t%s \t%s \t%s \t%s \n" %(i.kind,i.metadata.namespace,i.metadata.name,i.spec.cluster_ip,i.spec.ports))
 
if __name__ == '__main__':
    namespace_list = kubernetestools().get_namespace_list()
    pod_list = kubernetestools().get_pod_list()
    service = kubernetestools().get_service_list()
    print(namespace_list)
    print(pod_list)
    print(service)

到此这篇关于python使用kubernetes api访问集群的文章就介绍到这了,更多相关python kubernetes api访问集群内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://www.cnblogs.com/Dev0ps/p/14825543.html