一、python通过config文件执行api操作

https://www.cnblogs.com/zhangb8042/p/11444756.html

https://github.com/kubernetes-client/python/tree/master/examples

1)准备环境

cp .kube/config    kubeconfig.yaml
pip install kubernetes

2)获取k8s资源

from kubernetes import client, config
from os import path
import yaml

class k8sapi:
    def k8s_conn(self):
        config.kube_config.load_kube_config(config_file="kubeconfig.yaml")
        conn = client.CoreV1Api()
        return conn

    def namespaces(self):
        # 列出 namespaces
        conn = self.k8s_conn()
        ret = conn.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 services(self):
        # 列出所有的services
        conn = self.k8s_conn()
        ret = conn.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))

    def pods(self):
        # 列出所有的pod
        conn = self.k8s_conn()
        ret = conn.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 create(self):
        config.load_kube_config()
        with open(path.join(path.dirname(__file__), "/root/deploy.yaml")) as f:
            dep = yaml.safe_load(f)
            k8s_apps_v1 = client.AppsV1Api()
            resp = k8s_apps_v1.create_namespaced_deployment(
                body=dep, namespace="default")
            print("Deployment created. status='%s'" % resp.metadata.name)
    def delete(self):
        config.load_kube_config()
        k8s_core_v1 = client.CoreV1Api()
        resp = k8s_core_v1.delete_namespaced_pod(namespace="default", name='nginx-pod')
        print("delete Pod ")

if __name__ == '__main__':
    myk8s = k8sapi()
    myk8s.pods()
k8sinfo.py

3)创建pod使用的yaml文件

apiVersion: apps/v1
kind: Deployment
metadata:
  name: myapp
  namespace: default
  labels:
    app: myapp
spec:
  replicas: 1
  selector:
    matchLabels:
      app: myapp
  template:
    metadata:
      name: myapp-pod
      labels:
        app: myapp
    spec:
      containers:
      - name: myapp
        image: wangyanglinux/myapp:v2
        ports:
        - name: http
          containerPort: 80
View Code

 

 

二、获取app应用信息

获取app应用的基本信息, 有重复的

# coding: utf-8
import json,sys
import time
from kubernetes import client, config

region = sys.argv[1]
class myk8sinfo:
    def __init__(self):
        self.applists = []
    def k8s_conn(self):
        Token = "eyJhbGciOiJSUzI1NiIsImtpZCI6IiJ9.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJrdWJlLXN5c3RlbSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VjcmV0Lm5hbWUiOiJlbmlvdC1yZWFkZXItdG9rZW4tN2wydHgiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoiZW5pb3QtcmVhZGVyIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiNWFlNjVmMmUtOGQ5Ni0xMWU5LWIwNzUtMDAwZDNhYTA4OTA2Iiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50Omt1YmUtc3lzdGVtOmVuaW90LXJlYWRlciJ9.kUjZhtjQPHvxtcjonB-EAQeAVTXSdyLoiXAirRRJ6hrSPeP2WhgAzF1h2v6BwV1uZulnWZ9g0rZCY5RKlAIvnYeDrgsy1EAZ40u7N4I5DBPKAxbljZAjUcF_jO-OSBNDfSOCrUFgY_rmC5uROzXNe6jlVQ300vI3BUAkLf0Q3_LB0uFmMXutz2ZzUTOssJgMTUKMh0qutbTuwGgiDvpyBjqTgXpZOBcY1cNzuXoI3pBPnb2WiMcVoaB4rp3ov9m04KD6k1OqwB4MeR0UCz7hCA-8J7N2GYzGdAtDYoqRniJ5tkrfH2hQYjKLak0JfKg9vBrePCKCodUxTGp24QLdjQ"
        APISERVER = 'https://apaas0001:8443'
        configuration = client.Configuration()
        configuration.host = APISERVER
        configuration.verify_ssl = False
        configuration.api_key = {"authorization": "Bearer " + Token}
        client.Configuration.set_default(configuration)
        conn = client.CoreV1Api()
        return conn

    def podinfo(self,namespaced):
        conn = self.k8s_conn()
        ret = conn.list_namespaced_pod(namespaced)
        for i in ret.items:
            appinfo = {}
            image = i.spec.containers[0].image.split(":")[-1]
            cpu = i.spec.containers[0].resources.limits['cpu']
            memory = i.spec.containers[0].resources.limits['memory']
            namespace = i.metadata.namespace
            app = i.metadata.labels['app']
            appinfo['app'] = app
            appinfo['image'] = image
            appinfo['cpu'] = cpu
            appinfo['memory'] = memory
            appinfo['namespace'] = namespace
            self.applists.append(appinfo)

    def main(self):
        self.podinfo('arch')
        self.podinfo('enos')
        files = '%s.json' % region
        res = json.dumps(self.applists)
        with open(files,mode='w') as f:
            f.write(res)
apps_info.py
if __name__ == '__main__':
k8s = myk8sinfo()
k8s.main()

python apps_info.py region

结果:[{"app": "arch-rule-engine", "memory": "2Gi", "namespace": "arch", "image": "tag_rule-engine_20190613_002", "cpu": "1"},]

2) 2种方式,config或token

# coding: utf-8
import json,sys
import time
from kubernetes import client, config

region = sys.argv[1]
class myk8sinfo:
    def __init__(self):
        self.applists = []
    def k8s_conn(self):
        Token = "eyJhbGciOiJSUzI1NiIsImtpZCI6IiJ9.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJrdWJlLXN5c3RlbSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VjcmV0Lm5hbWUiOiJlbmlvdC1yZWFkZXItdG9rZW4tN2wydHgiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoiZW5pb3QtcmVhZGVyIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiNWFlNjVmMmUtOGQ5Ni0xMWU5LWIwNzUtMDAwZDNhYTA4OTA2Iiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50Omt1YmUtc3lzdGVtOmVuaW90LXJlYWRlciJ9.kUjZhtjQPHvxtcjonB-EAQeAVTXSdyLoiXAirRRJ6hrSPeP2WhgAzF1h2v6BwV1uZulnWZ9g0rZCY5RKlAIvnYeDrgsy1EAZ40u7N4I5DBPKAxbljZAjUcF_jO-OSBNDfSOCrUFgY_rmC5uROzXNe6jlVQ300vI3BUAkLf0Q3_LB0uFmMXutz2ZzUTOssJgMTUKMh0qutbTuwGgiDvpyBjqTgXpZOBcY1cNzuXoI3pBPnb2WiMcVoaB4rp3ov9m04KD6k1OqwB4MeR0UCz7hCA-8J7N2GYzGdAtDYoqRniJ5tkrfH2hQYjKLak0JfKg9vBrePCKCodUxTGp24QLdjQ"
        APISERVER = 'https://apaas0001:8443'
        configuration = client.Configuration()
        configuration.host = APISERVER
        configuration.verify_ssl = False
        configuration.api_key = {"authorization": "Bearer " + Token}
        client.Configuration.set_default(configuration)
        conn = client.CoreV1Api()
        return conn

    def k8s_conn2(self):
        config.kube_config.load_kube_config(config_file="kubeconfig.yaml")
        conn = client.CoreV1Api()
        return conn

    def podinfo(self,namespaced):
        conn = self.k8s_conn2()
        ret = conn.list_namespaced_pod(namespaced)
        for i in ret.items:
            appinfo = {}
            image = i.spec.containers[0].image.split(":")[-1]
            cpu = i.spec.containers[0].resources.limits['cpu']
            memory = i.spec.containers[0].resources.limits['memory']
            namespace = i.metadata.namespace
            app = i.metadata.labels['app']

            appinfo['app'] = app
            appinfo['image'] = image
            appinfo['cpu'] = cpu
            appinfo['memory'] = memory
            appinfo['namespace'] = namespace
            self.applists.append(appinfo)

    def main(self):
        self.podinfo('arch')
        self.podinfo('enos')
        files = '%s.json' % region
        res = json.dumps(self.applists)
        with open(files,mode='w') as f:
            f.write(res)


if __name__ == '__main__':
    k8s = myk8sinfo()
    k8s.main()
View Code

三、纯粹记录版本镜像

1)执行需给定环境

# coding: utf-8
import json,sys
from kubernetes import client, config

region = sys.argv[1]
class myk8sinfo:
    def __init__(self):
        self.images = []
    def k8s_conn(self):
        Token = "eyJhbGciOiJSUzI1NiIsImtpZCI6IiJ9.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJrdWJlLXN5c3RlbSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VjcmV0Lm5hbWUiOiJlbmlvdC1yZWFkZXItdG9rZW4tN2wydHgiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoiZW5pb3QtcmVhZGVyIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiNWFlNjVmMmUtOGQ5Ni0xMWU5LWIwNzUtMDAwZDNhYTA4OTA2Iiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50Omt1YmUtc3lzdGVtOmVuaW90LXJlYWRlciJ9.kUjZhtjQPHvxtcjonB-EAQeAVTXSdyLoiXAirRRJ6hrSPeP2WhgAzF1h2v6BwV1uZulnWZ9g0rZCY5RKlAIvnYeDrgsy1EAZ40u7N4I5DBPKAxbljZAjUcF_jO-OSBNDfSOCrUFgY_rmC5uROzXNe6jlVQ300vI3BUAkLf0Q3_LB0uFmMXutz2ZzUTOssJgMTUKMh0qutbTuwGgiDvpyBjqTgXpZOBcY1cNzuXoI3pBPnb2WiMcVoaB4rp3ov9m04KD6k1OqwB4MeR0UCz7hCA-8J7N2GYzGdAtDYoqRniJ5tkrfH2hQYjKLak0JfKg9vBrePCKCodUxTGp24QLdjQ"
        APISERVER = 'https://apaas0001:8443'
        configuration = client.Configuration()
        configuration.host = APISERVER
        configuration.verify_ssl = False
        configuration.api_key = {"authorization": "Bearer " + Token}
        client.Configuration.set_default(configuration)
        conn = client.CoreV1Api()
        return conn

    def k8s_conn2(self):
        config.kube_config.load_kube_config(config_file="kubeconfig.yaml")
        conn = client.CoreV1Api()
        return conn

    def podinfo(self,namespaced):
        conn = self.k8s_conn2()
        ret = conn.list_namespaced_pod(namespaced)
        for i in ret.items:
            image = i.spec.containers[0].image.split(":")[-1]
            if image not in self.images:
                self.images.append(image)
    def main(self):
        self.podinfo('arch')
        self.podinfo('enos')
        self.podinfo('uscada')
        files = '%s.json' % region
        res = json.dumps(self.images)
        with open(files,mode='w') as f:
            f.write(res)


if __name__ == '__main__':
    k8s = myk8sinfo()
    k8s.main()
k8simages.py

2)对比镜像

import json,sys
file1 = sys.argv[1]
file2 = sys.argv[2]

class Diff_images:
    def region_info(self,file):
        with open(file, 'r') as f:
            res = f.read()
        images = json.loads(res)
        return images

    def main(self):
        images1 = self.region_info(file1)
        images2 = self.region_info(file2)
        images1 = set(images1)
        images2 = set(images2)
        print(images2 - images1)

if __name__ == '__main__':
    diff = Diff_images()
    diff.main()

3)综合接口。https://github.com/kubernetes-client/python/blob/master/kubernetes/README.md

from kubernetes import client, config
from kubernetes.stream import stream
import datetime
from app.Public import datetime_to_time,Sort

class k8sCoreV1Api:
    def __init__(self, config_file):
        self.config_file = config_file
        self.config = config.kube_config.load_kube_config(config_file=self.config_file)
        self.v1 = client.CoreV1Api()

    def list_namespace(self):
        namespaces = []
        nid = 0
        for ns in self.v1.list_namespace().items:
            nsinfo = {}
            nid += 1
            name = ns.metadata.name
            status = ns.status.phase
            nsinfo['nid'] = nid
            nsinfo['name'] = name
            nsinfo['status'] = status
            namespaces.append(nsinfo)
        return namespaces

    def list_nodes(self):
        nodes = self.v1.list_node().items
        list_nodes = []
        for node in nodes:
            nodeinfo = {}
            for addres in node.status.addresses:
                if addres.type == 'Hostname':
                    nodeinfo['Hostname'] = addres.address
                if addres.type == 'InternalIP':
                    nodeinfo['InternalIP'] = addres.address
            nodeinfo['status'] = node.status.conditions[-1].type
            nodeinfo['cpu'] = node.status.allocatable['cpu']
            nodeinfo['memory'] = node.status.allocatable['memory']
            list_nodes.append(nodeinfo)
        return list_nodes

    def create_namespace(self, namespace):
        namespacelist = []
        for ns in self.list_namespace():
            namespacelist.append(ns['name'])
        if namespace not in namespacelist:
            create_namespace = {'apiVersion': 'v1', 'kind': 'Namespace',
                                'metadata': {'name': namespace, 'labels': {'name': namespace}}}
            res = self.v1.create_namespace(body=create_namespace)
            return res.metadata.name

    def list_namespaced_service(self, namespace):
        list_service = self.v1.list_namespaced_service(namespace).items
        service_list = []
        for service in list_service:
            serviceinfo = {}
            creation_timestamp = str(service.metadata.creation_timestamp + datetime.timedelta(hours=8))
            creation_timestamp = creation_timestamp.split("+")[0]
            app = service.spec.selector['app']
            cluster_ip = service.spec.cluster_ip
            target_port = service.spec.ports[0].target_port
            serviceinfo['app'] = app
            serviceinfo['cluster_ip'] = cluster_ip
            serviceinfo['target_port'] = target_port
            serviceinfo['creation_timestamp'] = creation_timestamp
            service_list.append(serviceinfo)
        return service_list

    def list_namespaced_service_name(self,namespace):
        list_service = self.v1.list_namespaced_service(namespace).items
        service_list = []
        for service in list_service:
            app = service.spec.selector['app']
            service_list.append(app)
        return service_list

    def create_namespaced_service(self,namespace,body):
        self.v1.create_namespaced_service(namespace,body)

    def read_namespaced_service(self,name,namespace):
        body = self.v1.read_namespaced_service(name, namespace)
        return body

    def replace_namespaced_service(self,name, namespace,port,targetPort):
        body = self.read_namespaced_service(name, namespace)
        body.spec.ports[0].name = "tcp-" + str(port)
        body.spec.ports[0].port = port
        body.spec.ports[0].target_port = targetPort
        self.v1.replace_namespaced_service(name, namespace, body)

    def delete_namespaced_service(self,name,namespace):
        self.v1.delete_namespaced_service(name, namespace)

    def create_namespaced_config_map(self,namespace,name,data):
        body = {'apiVersion': 'v1', 'kind': 'ConfigMap', 'metadata': {'name': name, 'namespace': namespace}}
        body['data'] = data
        self.v1.create_namespaced_config_map(namespace,body)

    def read_namespaced_config_map(self,name,namespace):
        body = self.v1.read_namespaced_config_map(name,namespace)
        return body

    def replace_namespaced_config_map(self,name, namespace,key,value):
        body = self.read_namespaced_config_map(name,namespace)
        body.data['key'] = key
        body.data['value'] = value
        self.v1.replace_namespaced_config_map(name, namespace, body)

    def create_namespaced_secret(self,name,namespace,mold,data):
        '''
        :param name:
        :param namespace:
        :param type:  kubernetes.io/rdb  or  Secret
        :param data: {'password': 'MTIzNDU2', 'username': 'YWRtaW4='}
        :return:
        '''
        body = {'apiVersion': 'v1', 'kind': 'Secret', 'metadata': {'name': name, 'namespace': namespace}, 'type':mold}
        body['data'] = data
        self.v1.create_namespaced_secret(namespace, body)

    def list_namespaced_secret(self,namespace):
        listsecret = self.v1.list_namespaced_secret(namespace).items
        secret_list = []
        for secret in listsecret:
            secret_list.append(secret.metadata.name)
        return secret_list

    def read_namespaced_secret(self,name, namespace):
        body = self.v1.read_namespaced_secret(name, namespace)
        return body

    def replace_namespaced_secret(self,name, namespace,data):
        body = self.read_namespaced_secret(name, namespace)
        body.data = {data["key"]:data["value"]}
        body.type = data["mold"]
        self.v1.replace_namespaced_secret(name, namespace, body)

    def list_namespaced_pod(self,namespace):
        listpod = self.v1.list_namespaced_pod(namespace).items
        pod_list = []
        for pod in listpod:
            podinfo = {}
            name = pod.metadata.name
            image = pod.spec.containers[0].image.split(":")[-1]
            node_name = pod.spec.node_name
            host_ip = pod.status.host_ip
            pod_ip = pod.status.pod_ip
            start_time = str(pod.status.start_time + datetime.timedelta(hours=8))
            start_time = start_time.split("+")[0]
            strftime = pod.status.start_time.strftime("%Y-%m-%d %H:%M:%S")
            timestamp = datetime_to_time(strftime)
            podinfo["name"] = name
            podinfo["image"] = image
            podinfo["node_name"] = node_name
            podinfo["host_ip"] = host_ip
            podinfo["pod_ip"] = pod_ip
            podinfo["start_time"] = start_time
            podinfo["timestamp"] = timestamp
            pod_list.append(podinfo)
        mysort = Sort()
        sort_pod_list = mysort.mergeSort(pod_list, 0, len(pod_list) - 1)
        sort_pod_list.reverse()
        return sort_pod_list

    def list_namespaced_pod_label_selector(self,namespace):
        list_pod = self.v1.list_namespaced_pod(namespace,label_selector='app=myapp')
        print(list_pod)

    def delete_namespaced_pod(self,name, namespace):
        self.v1.delete_namespaced_pod(name, namespace)

    def pod_exec(self,namespace, pod, container=""):
        api_instance = client.CoreV1Api()

        exec_command = [
            "/bin/sh",
            "-c",
            'TERM=xterm-256color; export TERM; [ -x /bin/bash ] '
            '&& ([ -x /usr/bin/script ] '
            '&& /usr/bin/script -q -c "/bin/bash" /dev/null || exec /bin/bash) '
            '|| exec /bin/sh']

        cont_stream = stream(api_instance.connect_get_namespaced_pod_exec,
                             name=pod,
                             namespace=namespace,
                             container=container,
                             command=exec_command,
                             stderr=True, stdin=True,
                             stdout=True, tty=True,
                             _preload_content=False
                             )

        return cont_stream

class k8sAppsV1Api:
    def __init__(self, config_file):
        self.config_file = config_file
        self.config = config.kube_config.load_kube_config(config_file=self.config_file)
        self.v1 = client.AppsV1Api()

    def list_deployment_for_all_namespaces(self):
        all_deployments = self.v1.list_deployment_for_all_namespaces().items
        all_list_deployments = []
        for deploy in all_deployments:
            deploymentsinfo = {}
            namespace = deploy.metadata.namespace
            name = deploy.metadata.name
            deploymentsinfo['namespace'] = namespace
            deploymentsinfo['name'] = name
            all_list_deployments.append(deploymentsinfo)
        return all_list_deployments

    def list_namespaced_deployment(self, namespace):
        deployments_list = self.v1.list_namespaced_deployment(namespace).items
        list_deployments = []
        for deployments in deployments_list:
            deploymentsinfo = {}
            name = deployments.metadata.name
            tag = deployments.spec.template.spec.containers[0].image.split(':')[-1]
            if tag == 'null':
                tag = ''
            cpu = deployments.spec.template.spec.containers[0].resources.limits['cpu']
            memory = deployments.spec.template.spec.containers[0].resources.limits['memory']
            replicas = deployments.spec.replicas
            ready_replicas = deployments.status.ready_replicas
            deploymentsinfo['name'] = name
            deploymentsinfo['images'] = tag
            deploymentsinfo['cpu'] = cpu
            deploymentsinfo['memory'] = memory
            deploymentsinfo['replicas'] = replicas
            deploymentsinfo['ready_replicas'] = ready_replicas
            list_deployments.append(deploymentsinfo)
        return list_deployments

    def list_namespaced_deployment_name(self, namespace):
        deployments_list = self.v1.list_namespaced_deployment(namespace).items
        list_name = []
        for deployments in deployments_list:
            name = deployments.metadata.name
            list_name.append(name)
        return list_name

    def read_namespaced_deployment(self, name, namespace):
        body = self.v1.read_namespaced_deployment(name, namespace)
        return body

    def replace_namespaced_deployment(self, name, namespace, tag, replicas):
        body = self.read_namespaced_deployment(name, namespace)
        imageurl = body.spec.template.spec.containers[0].image.split(':')[0]
        update_image = imageurl + ':' + tag
        body.spec.template.spec.containers[0].image = update_image
        body.spec.replicas = replicas
        data = {}
        deployment_body = self.v1.replace_namespaced_deployment(name, namespace, body)
        data['namespace'] = namespace
        data['name'] = name
        data['body'] = deployment_body
        return data

    def create_namespaced_deployment(self, namespace, body):
        data = self.v1.create_namespaced_deployment(namespace, body)
        return data

class k8sNetworkingV1beta1Api:
    def __init__(self,config_file):
        self.config_file=config_file
        self.config = config.kube_config.load_kube_config(config_file=self.config_file)
        self.v1 = client.NetworkingV1beta1Api()

    def get_body(self,namespace, name,host,port,route):
        body = {'apiVersion': 'networking.k8s.io/v1beta1', 'kind': 'Ingress',
         'metadata': {'name': name, 'namespace': namespace, 'labels': {'app': name},
                      'annotations': {'nginx.ingress.kubernetes.io/ssl-redirect': 'false'}}, 'spec': {'rules': [
            {'host': host,
             'http': {'paths': [{'backend': {'serviceName': name, 'servicePort': port}, 'path': route}]}}]}}
        return body

    def list_namespaced_ingress(self,namespace):
        list_ingress = self.v1.list_namespaced_ingress(namespace).items
        ingress_list = []
        for ingress in list_ingress:
            ingressinfo = {}
            creation_timestamp = str(ingress.metadata.creation_timestamp + datetime.timedelta(hours=8))
            creation_timestamp  = creation_timestamp.split("+")[0]
            host = ingress.spec.rules[0].host
            service_name = ingress.spec.rules[0].http.paths[0].backend.service_name
            service_port = ingress.spec.rules[0].http.paths[0].backend.service_port
            ingressinfo['service_name'] = service_name
            ingressinfo['host'] = host
            ingressinfo['service_port'] = service_port
            ingressinfo['creation_timestamp'] = creation_timestamp
            ingress_list.append(ingressinfo)
        return ingress_list

    def create_namespaced_ingress(self,namespace, name,host,port,route):
        body = self.get_body(namespace, name,host,port,route)
        self.v1.create_namespaced_ingress(namespace, body)

    def replace_namespaced_ingress(self,namespace, name,host,port,route):
        body = self.get_body(namespace, name, host, port, route)
        self.v1.replace_namespaced_ingress(name,namespace, body)

if __name__ == '__main__':
    config_file = 'config.config'
    test = k8sAppsV1Api(config_file)
    list_nodes = test.list_deployment_for_all_namespaces()
    print(list_nodes)
View Code

 3.1)简单的进行镜像替换

from kubernetes import client, config
import datetime

class k8sAppsV1Api():
    def __init__(self,config_file):
        self.config_file = config_file
        self.config = config.kube_config.load_kube_config(config_file=self.config_file)
        self.v1 = client.AppsV1Api()

    def read_deployment(self,name, namespace, update_image):
        body = self.v1.read_namespaced_deployment(name, namespace)
        old_image = body.spec.template.spec.containers[0].image
        msg = str(datetime.datetime.now()) + '  ' + "oldimage:" + old_image +'   '+ 'newimage:'+update_image
        with open('image_histroy.txt', mode='a', encoding='utf-8') as f:
            f.write(msg)
            f.write('\n')
        body.spec.template.spec.containers[0].image = update_image
        return body

    def replace_deployment(self,name, namespace, body):
        self.v1.replace_namespaced_deployment(name, namespace, body)


    def main(self):
        # enos myapp harbor-test.eniot.io/enos/myapp:v1
        with open('images',mode='r',encoding='utf-8') as f:
            for line in f:
                namespace = line.split()[0]
                app = line.split()[1]
                update_image = line.split()[2]
                body = self.read_deployment(app, namespace, update_image)
                self.replace_deployment(app, namespace, body)
                msg = str(datetime.datetime.now()) + "  " + "\033[0;32m{}中deployment:{}的镜像{}更新完成\033[0m".format(
                    namespace, app, update_image)
                print(msg)


if __name__ == '__main__':
    config_file = "config.yaml"
    v1 = k8sAppsV1Api(config_file)
    v1.main()
View Code

 3.3) token的使用。token可以来自dashboard

import urllib3
from pprint import pprint
from kubernetes import client
from os import path
import yaml

class K8sApi(object):
    def __init__(self):
        # self.config = config.kube_config.load_kube_config()
        urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
        self.configuration = client.Configuration()
        self.configuration.host = "https://192.168.85.110:6443"
        self.configuration.api_key[
            'authorization'] = 'Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IlZLYl8tTkJhTzVLb2IxSDA4Q2xaOEpBTGFpY2ZwNGx5T3h5SHBZOGJEUWsifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJrdWJlLXN5c3RlbSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VjcmV0Lm5hbWUiOiJkYXNoYm9hcmQtYWRtaW4tdG9rZW4tZjRyNTkiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoiZGFzaGJvYXJkLWFkbWluIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiOGMxNzUwYWQtNTliZC00ODI3LWEzMjMtOTI5ZDg4MTk1ZjgxIiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50Omt1YmUtc3lzdGVtOmRhc2hib2FyZC1hZG1pbiJ9.ognf5W_ipE_EeaSbGJbbMknkYtCn1KewG9dkX4yP_p-oEv-rKmSamGGZYpCerb9R8sZ-mbSeWqpIyZo_yMko49P1jjvcNSqss_H4fsQnfJduDR3DOPjC7ullL4h6P_kaFg5UxKGekkT_JKvRW1UlVa9fsOKnL-fj5RxbQ1lA-rJ8liCTnEej6tT1sQfYPe1YJT_Po8wEUZw3E1BoqfXnRUaGZ3uFJZgUHeQlDSTABiJRtMAcMZJ04ouh60T0BlMcsbi8kA2_qF4PIQmnaEsBiNhAn6TfAoqXRXaC1SLdw1lo5inDNZRaxYyurkkqtvrr1sDbZKtG1h24d2MjvphUMw'
        self.configuration.verify_ssl = False
        self.k8s_apps_v1 = client.AppsV1Api(client.ApiClient(self.configuration))
        self.Api_Instance = client.CoreV1Api(client.ApiClient(self.configuration))
        self.Api_Instance_Extensions = client.ExtensionsV1beta1Api(client.ApiClient(self.configuration))

    ####################################################################################################################

    def list_deployment(self, namespace="enos"):
        api_response = self.k8s_apps_v1.list_namespaced_deployment(namespace)
        return api_response

    def read_deployment(self, name="nginx-deployment", namespace="default"):
        api_response = self.k8s_apps_v1.read_namespaced_deployment(name, namespace)
        return api_response

    def create_deployment(self, file="deploy-nginx.yaml"):
        with open(path.join(path.dirname(__file__), file)) as f:
            dep = yaml.safe_load(f)
            resp = self.k8s_apps_v1.create_namespaced_deployment(
                body=dep, namespace="default")
            return resp

    def replace_deployment(self, file="deploy-nginx.yaml", name="nginx-deployment", namespace="default"):
        with open(path.join(path.dirname(__file__), file)) as f:
            dep = yaml.safe_load(f)
            resp = self.k8s_apps_v1.replace_namespaced_deployment(name, namespace,
                                                                  body=dep)
            return resp

    def delete_deployment(self, name="nginx-deployment", namespace="default"):
        api_response = self.k8s_apps_v1.delete_namespaced_deployment(name, namespace)
        return api_response

    ####################################################################################################################

    def list_namespace(self):
        api_response = self.Api_Instance.list_namespace()
        return api_response

    def read_namespace(self, name="default"):
        api_response = self.Api_Instance.read_namespace(name)
        return api_response

    def create_namespace(self, file="pod-nginx.yaml"):
        with open(path.join(path.dirname(__file__), file)) as f:
            dep = yaml.safe_load(f)
            api_response = self.Api_Instance.create_namespace(body=dep)
            return api_response

    def replace_namespace(self, file="pod-nginx.yaml", name="default"):
        with open(path.join(path.dirname(__file__), file)) as f:
            dep = yaml.safe_load(f)
        api_response = self.Api_Instance.replace_namespace(name, body=dep)
        return api_response

    def delete_namespace(self, name="default", namespace="default"):
        api_response = self.Api_Instance.delete_namespace(name)
        return api_response

    ####################################################################################################################

    def list_node(self):
        api_response = self.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

    def list_pod(self):
        api_response = self.Api_Instance.list_pod_for_all_namespaces()
        data = {}
        for i in api_response.items:
            data[i.metadata.name] = {"ip": i.status.pod_ip, "namespace": i.metadata.namespace}
        return data

    def read_pod(self, name="nginx-pod", namespace="default"):
        api_response = self.Api_Instance.read_namespaced_pod(name, namespace)
        return api_response

    def create_pod(self, file="pod-nginx.yaml", namespace="default"):
        with open(path.join(path.dirname(__file__), file)) as f:
            dep = yaml.safe_load(f)
            api_response = self.Api_Instance.create_namespaced_pod(namespace, body=dep)
            return api_response

    def replace_pod(self, file="pod-nginx.yaml", name="nginx-pod", namespace="default"):
        with open(path.join(path.dirname(__file__), file)) as f:
            dep = yaml.safe_load(f)
            api_response = self.Api_Instance.replace_namespaced_pod(name, namespace, body=dep)
        return api_response

    def delete_pod(self, name="nginx-pod", namespace="default"):
        api_response = self.Api_Instance.delete_namespaced_pod(name, namespace)
        return api_response

    ####################################################################################################################

    def list_service(self):
        api_response = self.Api_Instance.list_service_for_all_namespaces()
        return api_response

    def read_service(self, name="", namespace="default"):
        api_response = self.Api_Instance.read_namespaced_service(name, namespace)
        return api_response

    def create_service(self, file="service-nginx.yaml", namespace="default"):
        with open(path.join(path.dirname(__file__), file)) as f:
            dep = yaml.safe_load(f)
            api_response = self.Api_Instance.create_namespaced_service(namespace, body=dep)
            return api_response

    def replace_service(self, file="pod-nginx.yaml", name="hequan", namespace="default"):
        with open(path.join(path.dirname(__file__), file)) as f:
            dep = yaml.safe_load(f)
            api_response = self.Api_Instance.replace_namespaced_service(name, namespace, body=dep)
        return api_response

    def delete_service(self, name="hequan", namespace="default"):
        api_response = self.Api_Instance.delete_namespaced_service(name, namespace)
        return api_response

    ####################################################################################################################

    def list_ingress(self):
        api_response = self.Api_Instance_Extensions.list_ingress_for_all_namespaces()
        return api_response

    def read_ingress(self, name="", namespace="default"):
        api_response = self.Api_Instance_Extensions.read_namespaced_ingress(name, namespace)
        return api_response

    def create_ingress(self, file="ingress-nginx.yaml", namespace="default"):
        with open(path.join(path.dirname(__file__), file)) as f:
            dep = yaml.safe_load(f)
            api_response = self.Api_Instance_Extensions.create_namespaced_ingress(namespace, body=dep)
            return api_response

    def replace_ingress(self, name="", file="ingress-nginx.yaml", namespace="default"):
        with open(path.join(path.dirname(__file__), file)) as f:
            dep = yaml.safe_load(f)
            api_response = self.Api_Instance_Extensions.replace_namespaced_ingress(name=name, namespace=namespace,
                                                                                   body=dep)
            return api_response

    def delete_ingress(self, name="hequan", namespace="default"):
        api_response = self.Api_Instance_Extensions.delete_namespaced_ingress(name, namespace)
        return api_response

    #####################################################################################################################

    def list_stateful(self):
        api_response = self.k8s_apps_v1.list_stateful_set_for_all_namespaces()
        return api_response

    def read_stateful(self, name="nginx-deployment", namespace="default"):
        api_response = self.k8s_apps_v1.read_namespaced_stateful_set(name, namespace)
        return api_response

    def create_stateful(self, file="deploy-nginx.yaml"):
        with open(path.join(path.dirname(__file__), file)) as f:
            dep = yaml.safe_load(f)
            resp = self.k8s_apps_v1.create_namespaced_stateful_set(
                body=dep, namespace="default")
            return resp

    def replace_stateful(self, file="deploy-nginx.yaml", name="nginx-deployment", namespace="default"):
        with open(path.join(path.dirname(__file__), file)) as f:
            dep = yaml.safe_load(f)
            resp = self.k8s_apps_v1.replace_namespaced_stateful_set(name, namespace,
                                                                    body=dep)
            return resp

    def delete_stateful(self, name="nginx-deployment", namespace="default"):
        api_response = self.k8s_apps_v1.delete_namespaced_stateful_set(name, namespace)
        return api_response

    ####################################################################################################################

if __name__ == '__main__':
    def test():
        obj = K8sApi()
        ret = obj.list_deployment()
        pprint(ret)

    test()
View Code

3.4)封装

import urllib3
from kubernetes import client
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
class K8sApi(object):
    def __init__(self,url,token):
        self.url = url
        self.token = token
        self.configuration = client.Configuration()
        self.configuration.host = self.url
        self.configuration.api_key["authorization"] = "Bearer "+self.token
        self.configuration.verify_ssl = False
        self.AppsV1Api = client.AppsV1Api(client.ApiClient(self.configuration))
        self.CoreV1Api = client.CoreV1Api(client.ApiClient(self.configuration))
        self.ExtensionsV1beta1Api = client.ExtensionsV1beta1Api(client.ApiClient(self.configuration))

    def list_deployment_for_all_namespaces(self):
        all_deployments = self.AppsV1Api.list_deployment_for_all_namespaces().items
        all_list_deployments = []
        for deploy in all_deployments:
            deploymentsinfo = {}
            namespace = deploy.metadata.namespace
            name = deploy.metadata.name
            deploymentsinfo['namespace'] = namespace
            deploymentsinfo['name'] = name
            all_list_deployments.append(deploymentsinfo)
        return all_list_deployments

if __name__ == '__main__':
    url = "https://192.168.85.110:6443"
    token = "eyJhbGciOiJSUzI1NiIsImtpZCI6IlZLYl8tTkJhTzVLb2IxSDA4Q2xaOEpBTGFpY2ZwNGx5T3h5SHBZOGJEUWsifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJrdWJlLXN5c3RlbSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VjcmV0Lm5hbWUiOiJkYXNoYm9hcmQtYWRtaW4tdG9rZW4tZjRyNTkiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoiZGFzaGJvYXJkLWFkbWluIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiOGMxNzUwYWQtNTliZC00ODI3LWEzMjMtOTI5ZDg4MTk1ZjgxIiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50Omt1YmUtc3lzdGVtOmRhc2hib2FyZC1hZG1pbiJ9.ognf5W_ipE_EeaSbGJbbMknkYtCn1KewG9dkX4yP_p-oEv-rKmSamGGZYpCerb9R8sZ-mbSeWqpIyZo_yMko49P1jjvcNSqss_H4fsQnfJduDR3DOPjC7ullL4h6P_kaFg5UxKGekkT_JKvRW1UlVa9fsOKnL-fj5RxbQ1lA-rJ8liCTnEej6tT1sQfYPe1YJT_Po8wEUZw3E1BoqfXnRUaGZ3uFJZgUHeQlDSTABiJRtMAcMZJ04ouh60T0BlMcsbi8kA2_qF4PIQmnaEsBiNhAn6TfAoqXRXaC1SLdw1lo5inDNZRaxYyurkkqtvrr1sDbZKtG1h24d2MjvphUMw"
    apaas_test = K8sApi(url,token)
    apaas_conn = {}
    apaas_conn["apaas-test"] = apaas_test    
    list_nodes = apaas_conn["apaas-test"].list_deployment_for_all_namespaces()
    print(list_nodes)
View Code

 

posted on 2020-12-31 12:02  可口_可乐  阅读(3751)  评论(0编辑  收藏  举报