Kubernetes Python Client

发布时间:2020-10-09 11:20:49编辑:admin阅读(2348)

    一、概述

    Kubernetes官方维护的Python客户端client-python, 地址:https://github.com/kubernetes-client/python

    安装模块

    pip3 install kubernetes

     

     

    环境说明

    操作系统:centos 7.6

    k8s版本:1.18.1

    ip地址:192.168.31.74

    主机名:k8s-master

     

    操作系统:centos 7.6

    k8s版本:1.18.1

    ip地址:192.168.31.71

    主机名:k8s-node01

     

    二、获取API cluster URL与token

    获取Cluster URL地址

    登录到k8s-master节点,执行:

    # APISERVER=$(kubectl config view --minify | grep server | cut -f 2- -d ":" | tr -d " ")
    # echo $APISERVER
    https://192.168.31.74:6443
    下面python脚本要使用,我获取的是:https://192.168.31.74:6443

     

    创建k8s admin-token

    编辑新文件

    # mkdir -p /kube/role
    # cd /kube/role
    # vi admin-token.yaml

    内容如下:

    kind: ClusterRoleBinding
    apiVersion: rbac.authorization.k8s.io/v1beta1
    metadata:
      name: admin
      annotations:
        rbac.authorization.kubernetes.io/autoupdate: "true"
    roleRef:
      kind: ClusterRole
      name: cluster-admin
      apiGroup: rbac.authorization.k8s.io
    subjects:
    - kind: ServiceAccount
      name: admin
      namespace: kube-system
    ---
    apiVersion: v1
    kind: ServiceAccount
    metadata:
      name: admin
      namespace: kube-system
      labels:
        kubernetes.io/cluster-service: "true"
        addonmanager.kubernetes.io/mode: Reconcile

    执行yaml文件

    kubectl create -f admin-token.yaml

     

    获取token值

    # kubectl describe secret/$(kubectl get secret -nkube-system |grep admin|awk '{print $1}') -nkube-system|grep token:

    输出:

    token:      eyJhbGciOiJSUzI1NiIsImtxxxx

    由于token过长,这里用xxx代替

    最后将token与APISERVER地址返回内容复制到python client主机上, 供脚本使用.

     

    三、在python client主机上编写脚本

    本文采用的python版本为3.7.3,运行在一台centos 7.6的服务器上面。

     

    创建目录结构

    # mkdir -p /kube/auth
    # cd /kube/auth
    # vim token.txt

    将刚才获取的Token字符串复制到该文件,比如:eyJhbGciOiJSUzI1NiIsImtxxxx

    这里我们获取的token会引入到我们的脚本下, 作为bearer authorization的api key与远程k8s API建立认证连接.

     

    编写python client脚本

    获取的命名空间

    # !/usr/bin/python3
    # -*- 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.31.74:6443'
    
        def get_token(self):
            """
            获取token
            :return:
            """
            with open('token.txt', '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
    
    if __name__ == '__main__':
        namespace_list = KubernetesTools().get_namespace_list()
        print(namespace_list)

    执行输出:

    ['default', 'istio-system', 'kube-node-lease', 'kube-public', 'kube-system']

     

    注意:输出时,会有一段警告信息

    InsecureRequestWarning: Unverified HTTPS request is being made to host '192.168.31.74'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
      InsecureRequestWarning,

    这个是requests库提示警告,因为我是ip访问的,所以SSL验证会失败。但这个不影响。

     

    获取所有services

    在上面的代码基础上,再加一个方法

    def get_services(self):
            """
            获取所有services
            :return:
            """
            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))

    单独执行这个方法,会输出很多信息。由于由于输出过多,这里只列出我运行的一个flaskapp

    None     default     flaskapp-1     10.1.168.165     [{'name': 'flaskapp-port',
     'node_port': 30005,
     'port': 5000,
     'protocol': 'TCP',
     'target_port': 5000}]
    可以看到很多信息,包括service名,svc地址,以及node_port暴露的端口

     

    获取pod信息

    先登录k8s-master,查看目前运行的pod

    # kubectl get pods
    NAME                          READY   STATUS    RESTARTS   AGE
    flaskapp-1-5d96dbf59b-lhmp8   1/1     Running   4          23d

     

    在上面的代码基础上,再加一个方法

    def get_pod_info(self,namespaces,pod_name):
            """
            查看pod信息
            :param namespaces: 命令空间,比如:default
            :param pod_name: pod完整名称,比如:flaskapp-1-5d96dbf59b-lhmp8
            :return:
            """
            api = self.get_api()
            # 示例参数
            namespaces = "default"
            pod_name = "flaskapp-1-5d96dbf59b-lhmp8"
            resp = api.read_namespaced_pod(namespace=namespaces,name=pod_name)
            #详细信息
            print(resp)

    执行此方法,输出以下信息,由于输出过多,使用...省略

    {'api_version': 'v1',
     'kind': 'Pod',
      ...

    它会输出一段很长的json,里面包含了此pod的详细信息

     

    获取pod日志

    在上面的代码基础上,再加一个方法

    def get_pod_logs(self,namespaces,pod_name):
            """
            查看pod日志
            :param namespaces: 命令空间,比如:default
            :param pod_name: pod完整名称,比如:flaskapp-1-5d96dbf59b-lhmp8
            :return:
            """
            api = self.get_api()
            # 示例参数
            namespaces = "default"
            pod_name = "flaskapp-1-5d96dbf59b-lhmp8"
            """
            pretty美化输出
            tail_lines=200输出最近200行
            """
            log_content = api.read_namespaced_pod_log(pod_name, namespaces, pretty=True, tail_lines=200)
            print(log_content)

    执行此方法,输出以下信息:

    * Serving Flask app "app" (lazy loading)
     * Environment: production
       WARNING: Do not use the development server in a production environment.
       Use a production WSGI server instead.
     * Debug mode: on
     * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
     * Restarting with stat
     * Debugger is active!
     * Debugger PIN: 182-124-947

    这个是flask运行之后,输出的日志信息。

     

    想了解其他更多参考,请参考链接:

    https://blog.csdn.net/sinat_33431419/article/details/105223726

     

    备注:token直接写入到txt是不安全的,可以考虑将token写入到redis中,然后用python调用即可。

     

    本文参考链接:

    https://blog.csdn.net/hypon2016/article/details/99439309


关键字

上一篇: 初识Pandas

下一篇: pyecharts 安装及使用指南