佳木斯湛栽影视文化发展公司

主頁 > 知識庫 > Python使用Kubernetes API訪問集群

Python使用Kubernetes API訪問集群

熱門標簽:智能手機 鐵路電話系統(tǒng) 網(wǎng)站文章發(fā)布 檢查注冊表項 服務器配置 美圖手機 銀行業(yè)務 呼叫中心市場需求

通過將身份認證令牌直接傳給 API 服務器,可以避免使用 kubectl 代理,像這樣:
使用 grep/cut 方式:

# 查看所有的集群,因為你的 .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)

# 使用令牌玩轉(zhuǎn) API
curl -X GET $APISERVER/api --header "Authorization: Bearer $TOKEN" --insecure

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

python舉例:

目錄結(jié)構(gòu)

配置文件兩種方式

1、將集群中的~/.kube/config,重命名為kubeconfig.yaml
代碼:

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形式,獲取命令上文所示。
代碼:

# -*- 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)

到此這篇關(guān)于Python使用Kubernetes API訪問集群的文章就介紹到這了,更多相關(guān)Python Kubernetes API訪問集群內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

您可能感興趣的文章:
  • python3 kubernetes api的使用示例

標簽:新疆 河南 上海 滄州 紅河 沈陽 樂山 長治

巨人網(wǎng)絡通訊聲明:本文標題《Python使用Kubernetes API訪問集群》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡,涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266
    筠连县| 安远县| 神木县| 土默特右旗| 德保县| 大悟县| 怀宁县| 枣阳市| 宁波市| 元氏县| 金昌市| 云阳县| 绩溪县| 玉龙| 新蔡县| 新民市| 岳阳县| 洛隆县| 张家港市| 湖口县| 北碚区| 天津市| 高邮市| 长丰县| 琼海市| 雅江县| 武城县| 惠安县| 青冈县| 乐亭县| 宁陕县| 得荣县| 娱乐| 沐川县| 阜新市| 秦安县| 芦溪县| 江津市| 格尔木市| 阜平县| 孝义市|