kubernetes之python调用
安装
sudo pip3 install kubernetes
认证
首先引入SDK支持库。然后将 ~/.kube 的config文件的内容复制到本地目录,保存为文件kubeconfig.yaml,然后运行下面的python代码。
#使用 from kubernetes import client, config from kubernetes.stream import stream import yaml # kubeconfig.yaml保存的路径 config_file="/home/ics/kubeconfig.yaml" config.kube_config.load_kube_config(config_file=config_file) #获取API的CoreV1Api和BatchV1Api版本对象 Api_Instance = client.CoreV1Api() Api_Batch = client.BatchV1Api()
api使用
1、列出资源信息
1.1、命名空间
for ns in Api_Instance.list_namespace().items: print(ns.metadata.name)
获取所有的namespace名称
首先看下下面那是个客户端对象
下面我们还是执行查看列出命名空间
当打印Api_Instance.list_namespace()时
返回的信息如下:
{'api_version': 'v1', 'items': [{'api_version': None, 'kind': None, 'metadata': {'annotations': None, 'cluster_name': None, 'creation_timestamp': datetime.datetime(2022, 1, 20, 15, 19, 52, tzinfo=tzutc()), 'deletion_grace_period_seconds': None, 'deletion_timestamp': None, 'finalizers': None, 'generate_name': None, 'generation': None, 'labels': {'kubernetes.io/metadata.name': 'default'}, 'managed_fields': [{'api_version': 'v1', 'fields_type': 'FieldsV1', 'fields_v1': {'f:metadata': {'f:labels': {'.': {}, 'f:kubernetes.io/metadata.name': {}}}}, 'manager': 'kube-apiserver', 'operation': 'Update', 'time': datetime.datetime(2022, 1, 20, 15, 19, 52, tzinfo=tzutc())}], 'name': 'default', 'namespace': None, 'owner_references': None, 'resource_version': '211', 'self_link': None, 'uid': '85e2de18-3bca-4fe4-8efe-1d58717a0ad1'}, 'spec': {'finalizers': ['kubernetes']}, 'status': {'conditions': None, 'phase': 'Active'}}, {'api_version': None, 'kind': None, 'metadata': {'annotations': None, 'cluster_name': None, 'creation_timestamp': datetime.datetime(2022, 1, 20, 15, 19, 51, tzinfo=tzutc()), 'deletion_grace_period_seconds': None, 'deletion_timestamp': None, 'finalizers': None, 'generate_name': None, 'generation': None, 'labels': {'kubernetes.io/metadata.name': 'kube-node-lease'}, 'managed_fields': [{'api_version': 'v1', 'fields_type': 'FieldsV1', 'fields_v1': {'f:metadata': {'f:labels': {'.': {}, 'f:kubernetes.io/metadata.name': {}}}}, 'manager': 'kube-apiserver', 'operation': 'Update', 'time': datetime.datetime(2022, 1, 20, 15, 19, 51, tzinfo=tzutc())}], 'name': 'kube-node-lease', 'namespace': None, 'owner_references': None, 'resource_version': '57', 'self_link': None, 'uid': 'd9d66cab-1a71-4bc7-887d-17c8c0bb5cb9'}, 'spec': {'finalizers': ['kubernetes']}, 'status': {'conditions': None, 'phase': 'Active'}}, {'api_version': None, 'kind': None, 'metadata': {'annotations': None, 'cluster_name': None, 'creation_timestamp': datetime.datetime(2022, 1, 20, 15, 19, 51, tzinfo=tzutc()), 'deletion_grace_period_seconds': None, 'deletion_timestamp': None, 'finalizers': None, 'generate_name': None, 'generation': None, 'labels': {'kubernetes.io/metadata.name': 'kube-public'}, 'managed_fields': [{'api_version': 'v1', 'fields_type': 'FieldsV1', 'fields_v1': {'f:metadata': {'f:labels': {'.': {}, 'f:kubernetes.io/metadata.name': {}}}}, 'manager': 'kube-apiserver', 'operation': 'Update', 'time': datetime.datetime(2022, 1, 20, 15, 19, 51, tzinfo=tzutc())}], 'name': 'kube-public', 'namespace': None, 'owner_references': None, 'resource_version': '53', 'self_link': None, 'uid': 'a331d90f-8e07-4e87-9c41-d87d29864677'}, 'spec': {'finalizers': ['kubernetes']}, 'status': {'conditions': None, 'phase': 'Active'}}, {'api_version': None, 'kind': None, 'metadata': {'annotations': None, 'cluster_name': None, 'creation_timestamp': datetime.datetime(2022, 1, 20, 15, 19, 48, tzinfo=tzutc()), 'deletion_grace_period_seconds': None, 'deletion_timestamp': None, 'finalizers': None, 'generate_name': None, 'generation': None, 'labels': {'kubernetes.io/metadata.name': 'kube-system'}, 'managed_fields': [{'api_version': 'v1', 'fields_type': 'FieldsV1', 'fields_v1': {'f:metadata': {'f:labels': {'.': {}, 'f:kubernetes.io/metadata.name': {}}}}, 'manager': 'Go-http-client', 'operation': 'Update', 'time': datetime.datetime(2022, 1, 20, 15, 19, 48, tzinfo=tzutc())}], 'name': 'kube-system', 'namespace': None, 'owner_references': None, 'resource_version': '12', 'self_link': None, 'uid': 'c51c2c55-5673-495e-b10d-a86fabccef77'}, 'spec': {'finalizers': ['kubernetes']}, 'status': {'conditions': None, 'phase': 'Active'}}], 'kind': 'NamespaceList', 'metadata': {'_continue': None, 'remaining_item_count': None, 'resource_version': '4195', 'self_link': None}}
可见,所有的命名空间都在返回的item下。每个命名空间就是一个字典,这个命名空间的名称就在字典的元数据字段下的name下
下面还有个资源版本。
下面看单个命名空间的详细情况:每个命名空间的名称都在元数据的名称下面
列出命名空间是个对象吧。返回的是类似于字典的那种数据。点获取返回数据中的items数据。items下就是一个个列表元素了,每个元素都是一个字典,每个字典都是一个命名空间的信息
print(type(Api_Instance.list_namespace())) #<class 'kubernetes.client.models.v1_namespace_list.V1NamespaceList'>
print(type(Api_Instance.list_namespace().items)) #<class 'list'>
所以,可以for循环这个列表,对每个命名空间,获取到命名空间的名称
1.2、k8s节点
#列出所有的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 allNode=list_node() print(allNode)
上面的程序还是不变,实例化一个api对象,可以看到返回的是个字典
{ 'mcwk8s-master': { 'name': 'mcwk8s-master', 'status': 'Ready', 'ip': '10.0.0.4', 'kubelet_version': 'v1.23.1', 'os_image': 'CentOS Linux 7 (Core)' }, 'mcwk8s-node1': { 'name': 'mcwk8s-node1', 'status': 'Ready', 'ip': '10.0.0.5', 'kubelet_version': 'v1.23.1', 'os_image': 'CentOS Linux 7 (Core)' }, 'mcwk8s-node2': { 'name': 'mcwk8s-node2', 'status': 'Ready', 'ip': '10.0.0.6', 'kubelet_version': 'v1.23.1', 'os_image': 'CentOS Linux 7 (Core)' } }
如下图可以看出,将集群节点信息都获取到了
下面我们看单个节点都有哪些信息
我们看下命令行获取的信息是什么:
上面是自定义函数封装的数据。那么调用的时候返回的是什么呢?返回的是一个类似于字典数据。跟我们刚才列出命名空间看的是一样的数据类型,数据结构也类似
这是列出节点直接返回的数据,我们需要的节点信息详情还是在items下,还是可以点来调用。然后items下就是个列表,每个节点都是一个列表元素了,我们共有三个节点
{'api_version': 'v1', 'items': [{'api_version': None, 'kind': None, 'metadata': {'annotations': {'flannel.alpha.coreos.com/backend-data': '{"VNI":1,"VtepMAC":"ca:9d:fb:2c:b7:22"}', 'flannel.alpha.coreos.com/backend-type': 'vxlan', 'flannel.alpha.coreos.com/kube-subnet-manager': 'true', 'flannel.alpha.coreos.com/public-ip': '10.0.0.4', 'kubeadm.alpha.kubernetes.io/cri-socket': '/var/run/dockershim.sock', 'node.alpha.kubernetes.io/ttl': '0', 'volumes.kubernetes.io/controller-managed-attach-detach': 'true'}, 'cluster_name': None, 'creation_timestamp': datetime.datetime(2022, 1, 20, 15, 19, 48, tzinfo=tzutc()), 'deletion_grace_period_seconds': None, 'deletion_timestamp': None, 'finalizers': None, 'generate_name': None, 'generation': None, 'labels': {'beta.kubernetes.io/arch': 'amd64', 'beta.kubernetes.io/os': 'linux', 'kubernetes.io/arch': 'amd64', 'kubernetes.io/hostname': 'mcwk8s-master', 'kubernetes.io/os': 'linux', 'node-role.kubernetes.io/control-plane': '', 'node-role.kubernetes.io/master': '', 'node.kubernetes.io/exclude-from-external-load-balancers': ''}, 'managed_fields': [{'api_version': 'v1', 'fields_type': 'FieldsV1', 'fields_v1': {'f:metadata': {'f:annotations': {'.': {}, 'f:kubeadm.alpha.kubernetes.io/cri-socket': {}, 'f:volumes.kubernetes.io/controller-managed-attach-detach': {}}, 'f:labels': {'.': {}, 'f:beta.kubernetes.io/arch': {}, 'f:beta.kubernetes.io/os': {}, 'f:kubernetes.io/arch': {}, 'f:kubernetes.io/hostname': {}, 'f:kubernetes.io/os': {}, 'f:node-role.kubernetes.io/control-plane': {}, 'f:node-role.kubernetes.io/master': {}, 'f:node.kubernetes.io/exclude-from-external-load-balancers': {}}}}, 'manager': 'Go-http-client', 'operation': 'Update', 'time': datetime.datetime(2022, 1, 20, 15, 19, 54, tzinfo=tzutc())}, {'api_version': 'v1', 'fields_type': 'FieldsV1', 'fields_v1': {'f:metadata': {'f:annotations': {'f:flannel.alpha.coreos.com/backend-data': {}, 'f:flannel.alpha.coreos.com/backend-type': {}, 'f:flannel.alpha.coreos.com/kube-subnet-manager': {}, 'f:flannel.alpha.coreos.com/public-ip': {}}}, 'f:status': {'f:conditions': {'k:{"type":"NetworkUnavailable"}': {'.': {}, 'f:lastHeartbeatTime': {}, 'f:lastTransitionTime': {}, 'f:message': {}, 'f:reason': {}, 'f:status': {}, 'f:type': {}}}}}, 'manager': 'flanneld', 'operation': 'Update', 'time': datetime.datetime(2022, 1, 20, 15, 30, 38, tzinfo=tzutc())}, {'api_version': 'v1', 'fields_type': 'FieldsV1', 'fields_v1': {'f:status': {'f:allocatable': {'f:ephemeral-storage': {}}, 'f:conditions': {'k:{"type":"DiskPressure"}': {'f:lastHeartbeatTime': {}}, 'k:{"type":"MemoryPressure"}': {'f:lastHeartbeatTime': {}}, 'k:{"type":"PIDPressure"}': {'f:lastHeartbeatTime': {}}, 'k:{"type":"Ready"}': {'f:lastHeartbeatTime': {}, 'f:lastTransitionTime': {}, 'f:message': {}, 'f:reason': {}, 'f:status': {}}}, 'f:images': {}}}, 'manager': 'Go-http-client', 'operation': 'Update', 'time': datetime.datetime(2022, 1, 20, 15, 30, 45, tzinfo=tzutc())}, {'api_version': 'v1', 'fields_type': 'FieldsV1', 'fields_v1': {'f:metadata': {'f:annotations': {'f:node.alpha.kubernetes.io/ttl': {}}}, 'f:spec': {'f:podCIDR': {}, 'f:podCIDRs': {'.': {}, 'v:"10.244.0.0/24"': {}}, 'f:taints': {}}}, 'manager': 'kube-controller-manager', 'operation': 'Update', 'time': datetime.datetime(2022, 1, 20, 15, 30, 45, tzinfo=tzutc())}], 'name': 'mcwk8s-master', 'namespace': None, 'owner_references': None, 'resource_version': '8858', 'self_link': None, 'uid': '48fad458-0655-4794-8689-b0afca67cefa'}, 'spec': {'config_source': None, 'external_id': None, 'pod_cid_rs': ['10.244.0.0/24'], 'pod_cidr': '10.244.0.0/24', 'provider_id': None, 'taints': [{'effect': 'NoSchedule', 'key': 'node-role.kubernetes.io/master', 'time_added': None, 'value': None}], 'unschedulable': None}, 'status': {'addresses': [{'address': '10.0.0.4', 'type': 'InternalIP'}, {'address': 'mcwk8s-master', 'type': 'Hostname'}], 'allocatable': {'cpu': '2', 'ephemeral-storage': '17804191305', 'hugepages-2Mi': '0', 'memory': '2069796Ki', 'pods': '110'}, 'capacity': {'cpu': '2', 'ephemeral-storage': '18866Mi', 'hugepages-2Mi': '0', 'memory': '2172196Ki', 'pods': '110'}, 'conditions': [{'last_heartbeat_time': datetime.datetime(2022, 1, 20, 15, 30, 38, tzinfo=tzutc()), 'last_transition_time': datetime.datetime(2022, 1, 20, 15, 30, 38, tzinfo=tzutc()), 'message': 'Flannel is running on this ' 'node', 'reason': 'FlannelIsUp', 'status': 'False', 'type': 'NetworkUnavailable'}, {'last_heartbeat_time': datetime.datetime(2022, 2, 22, 15, 47, 16, tzinfo=tzutc()), 'last_transition_time': datetime.datetime(2022, 1, 20, 15, 19, 39, tzinfo=tzutc()), 'message': 'kubelet has sufficient ' 'memory available', 'reason': 'KubeletHasSufficientMemory', 'status': 'False', 'type': 'MemoryPressure'}, {'last_heartbeat_time': datetime.datetime(2022, 2, 22, 15, 47, 16, tzinfo=tzutc()), 'last_transition_time': datetime.datetime(2022, 1, 20, 15, 19, 39, tzinfo=tzutc()), 'message': 'kubelet has no disk ' 'pressure', 'reason': 'KubeletHasNoDiskPressure', 'status': 'False', 'type': 'DiskPressure'}, {'last_heartbeat_time': datetime.datetime(2022, 2, 22, 15, 47, 16, tzinfo=tzutc()), 'last_transition_time': datetime.datetime(2022, 1, 20, 15, 19, 39, tzinfo=tzutc()), 'message': 'kubelet has sufficient PID ' 'available', 'reason': 'KubeletHasSufficientPID', 'status': 'False', 'type': 'PIDPressure'}, {'last_heartbeat_time': datetime.datetime(2022, 2, 22, 15, 47, 16, tzinfo=tzutc()), 'last_transition_time': datetime.datetime(2022, 1, 20, 15, 30, 45, tzinfo=tzutc()), 'message': 'kubelet is posting ready ' 'status', 'reason': 'KubeletReady', 'status': 'True', 'type': 'Ready'}], 'config': None, 'daemon_endpoints': {'kubelet_endpoint': {'port': 10250}}, 'images': [{'names': ['registry.aliyuncs.com/google_containers/etcd@sha256:64b9ea357325d5db9f8a723dcf503b5a449177b17ac87d69481e126bb724c263', 'registry.aliyuncs.com/google_containers/etcd:3.5.1-0'], 'size_bytes': 292558922}, {'names': ['centos@sha256:a27fd8080b517143cbbbab9dfb7c8571c40d67d534bbdee55bd6c473f432b177', 'centos:latest'], 'size_bytes': 231268856}, {'names': ['registry.aliyuncs.com/google_containers/kube-apiserver@sha256:63ede81b7e1fbb51669f4ee461481815f50eeed1f95e48558e3b8c3dace58a0f', 'registry.aliyuncs.com/google_containers/kube-apiserver:v1.23.2'], 'size_bytes': 135162256}, {'names': ['registry.aliyuncs.com/google_containers/kube-controller-manager@sha256:d329c1d6597aa53939e5bd8aa5a0c856357324e5c1eae48d6b70fcbbbdf966c7', 'registry.aliyuncs.com/google_containers/kube-controller-manager:v1.23.2'], 'size_bytes': 124971725}, {'names': ['registry.aliyuncs.com/google_containers/kube-proxy@sha256:ba5545c288ffd91a94a57c665355e7585c650122088bb818d06b74f2ce0c4a98', 'registry.aliyuncs.com/google_containers/kube-proxy:v1.23.2'], 'size_bytes': 112327826}, {'names': ['quay.io/coreos/flannel@sha256:9a296fbb67790659adc3701e287adde3c59803b7fcefe354f1fc482840cdb3d9', 'quay.io/coreos/flannel:v0.15.1'], 'size_bytes': 69516425}, {'names': ['registry.aliyuncs.com/google_containers/kube-scheduler@sha256:24f19a1f6aaa54110dde609168a599e15746e0756352e100503a8a4de44af3f1', 'registry.aliyuncs.com/google_containers/kube-scheduler:v1.23.2'], 'size_bytes': 53488333}, {'names': ['registry.aliyuncs.com/google_containers/coredns@sha256:5b6ec0d6de9baaf3e92d0f66cd96a25b9edbce8716f5f15dcd1a616b3abd590e', 'registry.aliyuncs.com/google_containers/coredns:v1.8.6'], 'size_bytes': 46829283}, {'names': ['rancher/mirrored-flannelcni-flannel-cni-plugin@sha256:bfe8f30c74bc6f31eba0cc6659e396dbdd5ab171314ed542cc238ae046660ede', 'rancher/mirrored-flannelcni-flannel-cni-plugin:v1.0.0'], 'size_bytes': 9031177}, {'names': ['registry.aliyuncs.com/google_containers/pause@sha256:3d380ca8864549e74af4b29c10f9cb0956236dfb01c40ca076fb6c37253234db', 'registry.aliyuncs.com/google_containers/pause:3.6'], 'size_bytes': 682696}], 'node_info': {'architecture': 'amd64', 'boot_id': 'af5ad723-af18-4deb-9677-1650a429e68a', 'container_runtime_version': 'docker://20.10.12', 'kernel_version': '3.10.0-693.el7.x86_64', 'kube_proxy_version': 'v1.23.1', 'kubelet_version': 'v1.23.1', 'machine_id': 'ae0fe0e438654fb382077a165b544e8f', 'operating_system': 'linux', 'os_image': 'CentOS Linux 7 (Core)', 'system_uuid': '201E4D56-B6CB-23E5-BE25-098052A23AB7'}, 'phase': None, 'volumes_attached': None, 'volumes_in_use': None}}, {'api_version': None, 'kind': None, 'metadata': {'annotations': {'flannel.alpha.coreos.com/backend-data': '{"VNI":1,"VtepMAC":"ae:b6:47:92:7d:7e"}', 'flannel.alpha.coreos.com/backend-type': 'vxlan', 'flannel.alpha.coreos.com/kube-subnet-manager': 'true', 'flannel.alpha.coreos.com/public-ip': '10.0.0.5', 'kubeadm.alpha.kubernetes.io/cri-socket': '/var/run/dockershim.sock', 'node.alpha.kubernetes.io/ttl': '0', 'volumes.kubernetes.io/controller-managed-attach-detach': 'true'}, 'cluster_name': None, 'creation_timestamp': datetime.datetime(2022, 1, 20, 15, 31, 45, tzinfo=tzutc()), 'deletion_grace_period_seconds': None, 'deletion_timestamp': None, 'finalizers': None, 'generate_name': None, 'generation': None, 'labels': {'beta.kubernetes.io/arch': 'amd64', 'beta.kubernetes.io/os': 'linux', 'kubernetes.io/arch': 'amd64', 'kubernetes.io/hostname': 'mcwk8s-node1', 'kubernetes.io/os': 'linux'}, 'managed_fields': [{'api_version': 'v1', 'fields_type': 'FieldsV1', 'fields_v1': {'f:metadata': {'f:annotations': {'.': {}, 'f:kubeadm.alpha.kubernetes.io/cri-socket': {}, 'f:volumes.kubernetes.io/controller-managed-attach-detach': {}}, 'f:labels': {'.': {}, 'f:beta.kubernetes.io/arch': {}, 'f:beta.kubernetes.io/os': {}, 'f:kubernetes.io/arch': {}, 'f:kubernetes.io/hostname': {}, 'f:kubernetes.io/os': {}}}}, 'manager': 'Go-http-client', 'operation': 'Update', 'time': datetime.datetime(2022, 1, 20, 15, 31, 50, tzinfo=tzutc())}, {'api_version': 'v1', 'fields_type': 'FieldsV1', 'fields_v1': {'f:metadata': {'f:annotations': {'f:flannel.alpha.coreos.com/backend-data': {}, 'f:flannel.alpha.coreos.com/backend-type': {}, 'f:flannel.alpha.coreos.com/kube-subnet-manager': {}, 'f:flannel.alpha.coreos.com/public-ip': {}}}, 'f:status': {'f:conditions': {'k:{"type":"NetworkUnavailable"}': {'.': {}, 'f:lastHeartbeatTime': {}, 'f:lastTransitionTime': {}, 'f:message': {}, 'f:reason': {}, 'f:status': {}, 'f:type': {}}}}}, 'manager': 'flanneld', 'operation': 'Update', 'time': datetime.datetime(2022, 1, 20, 15, 37, 22, tzinfo=tzutc())}, {'api_version': 'v1', 'fields_type': 'FieldsV1', 'fields_v1': {'f:metadata': {'f:annotations': {'f:node.alpha.kubernetes.io/ttl': {}}}, 'f:spec': {'f:podCIDR': {}, 'f:podCIDRs': {'.': {}, 'v:"10.244.1.0/24"': {}}}}, 'manager': 'kube-controller-manager', 'operation': 'Update', 'time': datetime.datetime(2022, 2, 22, 14, 31, 52, tzinfo=tzutc())}, {'api_version': 'v1', 'fields_type': 'FieldsV1', 'fields_v1': {'f:status': {'f:allocatable': {'f:ephemeral-storage': {}}, 'f:capacity': {'f:ephemeral-storage': {}}, 'f:conditions': {'k:{"type":"DiskPressure"}': {'f:lastHeartbeatTime': {}, 'f:lastTransitionTime': {}, 'f:message': {}, 'f:reason': {}, 'f:status': {}}, 'k:{"type":"MemoryPressure"}': {'f:lastHeartbeatTime': {}, 'f:lastTransitionTime': {}, 'f:message': {}, 'f:reason': {}, 'f:status': {}}, 'k:{"type":"PIDPressure"}': {'f:lastHeartbeatTime': {}, 'f:lastTransitionTime': {}, 'f:message': {}, 'f:reason': {}, 'f:status': {}}, 'k:{"type":"Ready"}': {'f:lastHeartbeatTime': {}, 'f:lastTransitionTime': {}, 'f:message': {}, 'f:reason': {}, 'f:status': {}}}, 'f:images': {}, 'f:nodeInfo': {'f:bootID': {}}}}, 'manager': 'Go-http-client', 'operation': 'Update', 'time': datetime.datetime(2022, 2, 22, 14, 34, 35, tzinfo=tzutc())}], 'name': 'mcwk8s-node1', 'namespace': None, 'owner_references': None, 'resource_version': '8784', 'self_link': None, 'uid': 'fcbdbbcc-db01-46ea-aadd-018389c5b2cc'}, 'spec': {'config_source': None, 'external_id': None, 'pod_cid_rs': ['10.244.1.0/24'], 'pod_cidr': '10.244.1.0/24', 'provider_id': None, 'taints': None, 'unschedulable': None}, 'status': {'addresses': [{'address': '10.0.0.5', 'type': 'InternalIP'}, {'address': 'mcwk8s-node1', 'type': 'Hostname'}], 'allocatable': {'cpu': '1', 'ephemeral-storage': '17804191305', 'hugepages-2Mi': '0', 'memory': '897296Ki', 'pods': '110'}, 'capacity': {'cpu': '1', 'ephemeral-storage': '18866Mi', 'hugepages-2Mi': '0', 'memory': '999696Ki', 'pods': '110'}, 'conditions': [{'last_heartbeat_time': datetime.datetime(2022, 2, 22, 14, 34, 46, tzinfo=tzutc()), 'last_transition_time': datetime.datetime(2022, 2, 22, 14, 34, 46, tzinfo=tzutc()), 'message': 'Flannel is running on this ' 'node', 'reason': 'FlannelIsUp', 'status': 'False', 'type': 'NetworkUnavailable'}, {'last_heartbeat_time': datetime.datetime(2022, 2, 22, 15, 46, 24, tzinfo=tzutc()), 'last_transition_time': datetime.datetime(2022, 2, 22, 14, 34, 35, tzinfo=tzutc()), 'message': 'kubelet has sufficient ' 'memory available', 'reason': 'KubeletHasSufficientMemory', 'status': 'False', 'type': 'MemoryPressure'}, {'last_heartbeat_time': datetime.datetime(2022, 2, 22, 15, 46, 24, tzinfo=tzutc()), 'last_transition_time': datetime.datetime(2022, 2, 22, 14, 34, 35, tzinfo=tzutc()), 'message': 'kubelet has no disk ' 'pressure', 'reason': 'KubeletHasNoDiskPressure', 'status': 'False', 'type': 'DiskPressure'}, {'last_heartbeat_time': datetime.datetime(2022, 2, 22, 15, 46, 24, tzinfo=tzutc()), 'last_transition_time': datetime.datetime(2022, 2, 22, 14, 34, 35, tzinfo=tzutc()), 'message': 'kubelet has sufficient PID ' 'available', 'reason': 'KubeletHasSufficientPID', 'status': 'False', 'type': 'PIDPressure'}, {'last_heartbeat_time': datetime.datetime(2022, 2, 22, 15, 46, 24, tzinfo=tzutc()), 'last_transition_time': datetime.datetime(2022, 2, 22, 14, 34, 45, tzinfo=tzutc()), 'message': 'kubelet is posting ready ' 'status', 'reason': 'KubeletReady', 'status': 'True', 'type': 'Ready'}], 'config': None, 'daemon_endpoints': {'kubelet_endpoint': {'port': 10250}}, 'images': [{'names': ['centos@sha256:a27fd8080b517143cbbbab9dfb7c8571c40d67d534bbdee55bd6c473f432b177', 'centos:latest'], 'size_bytes': 231268856}, {'names': ['registry.cn-hangzhou.aliyuncs.com/google_containers/heapster-grafana-amd64@sha256:720cfe4a35e1065dbde42d2312fb827df200ced867353e3afe497c81c8aa4a56', 'registry.cn-hangzhou.aliyuncs.com/google_containers/heapster-grafana-amd64:v5.0.4'], 'size_bytes': 170981547}, {'names': ['registry.aliyuncs.com/google_containers/kube-proxy@sha256:ba5545c288ffd91a94a57c665355e7585c650122088bb818d06b74f2ce0c4a98', 'registry.aliyuncs.com/google_containers/kube-proxy:v1.23.2'], 'size_bytes': 112327826}, {'names': ['nginx@sha256:e3456c851a152494c3e4ff5fcc26f240206abac0c9d794affb40e0714846c451', 'nginx:1.7.9'], 'size_bytes': 91664166}, {'names': ['ghcr.io/weaveworks/launcher/scope@sha256:8591bb11d72f784f784ac8414660759d40b7c0d8819011660c1cc94271480a83', 'ghcr.io/weaveworks/launcher/scope:1.13.2'], 'size_bytes': 84949942}, {'names': ['registry.cn-hangzhou.aliyuncs.com/google_containers/heapster-amd64@sha256:dccaabb0c20cf05c29baefa1e9bf0358b083ccc0fab492b9b3b47fb7e4db5472', 'registry.cn-hangzhou.aliyuncs.com/google_containers/heapster-amd64:v1.5.4'], 'size_bytes': 75318342}, {'names': ['quay.io/coreos/flannel@sha256:9a296fbb67790659adc3701e287adde3c59803b7fcefe354f1fc482840cdb3d9', 'quay.io/coreos/flannel:v0.15.1'], 'size_bytes': 69516425}, {'names': ['kubernetesui/metrics-scraper@sha256:36d5b3f60e1a144cc5ada820910535074bdf5cf73fb70d1ff1681537eef4e172', 'kubernetesui/metrics-scraper:v1.0.7'], 'size_bytes': 34446077}, {'names': ['rancher/mirrored-flannelcni-flannel-cni-plugin@sha256:bfe8f30c74bc6f31eba0cc6659e396dbdd5ab171314ed542cc238ae046660ede', 'rancher/mirrored-flannelcni-flannel-cni-plugin:v1.0.0'], 'size_bytes': 9031177}, {'names': ['alpine@sha256:66790a2b79e1ea3e1dabac43990c54aca5d1ddf268d9a5a0285e4167c8b24475', 'alpine:3.6'], 'size_bytes': 4028004}, {'names': ['registry.aliyuncs.com/google_containers/pause@sha256:3d380ca8864549e74af4b29c10f9cb0956236dfb01c40ca076fb6c37253234db', 'registry.aliyuncs.com/google_containers/pause:3.6'], 'size_bytes': 682696}], 'node_info': {'architecture': 'amd64', 'boot_id': '801e3e29-f43f-4df1-9232-d83fb1070489', 'container_runtime_version': 'docker://20.10.12', 'kernel_version': '3.10.0-693.el7.x86_64', 'kube_proxy_version': 'v1.23.1', 'kubelet_version': 'v1.23.1', 'machine_id': 'ca33954a827a437bb4c598cfeb081bd6', 'operating_system': 'linux', 'os_image': 'CentOS Linux 7 (Core)', 'system_uuid': 'C4594D56-2374-FA86-4266-FA13700BA30B'}, 'phase': None, 'volumes_attached': None, 'volumes_in_use': None}}, {'api_version': None, 'kind': None, 'metadata': {'annotations': {'flannel.alpha.coreos.com/backend-data': '{"VNI":1,"VtepMAC":"f6:ae:0a:32:45:2a"}', 'flannel.alpha.coreos.com/backend-type': 'vxlan', 'flannel.alpha.coreos.com/kube-subnet-manager': 'true', 'flannel.alpha.coreos.com/public-ip': '10.0.0.6', 'kubeadm.alpha.kubernetes.io/cri-socket': '/var/run/dockershim.sock', 'node.alpha.kubernetes.io/ttl': '0', 'volumes.kubernetes.io/controller-managed-attach-detach': 'true'}, 'cluster_name': None, 'creation_timestamp': datetime.datetime(2022, 1, 20, 15, 31, 56, tzinfo=tzutc()), 'deletion_grace_period_seconds': None, 'deletion_timestamp': None, 'finalizers': None, 'generate_name': None, 'generation': None, 'labels': {'beta.kubernetes.io/arch': 'amd64', 'beta.kubernetes.io/os': 'linux', 'kubernetes.io/arch': 'amd64', 'kubernetes.io/hostname': 'mcwk8s-node2', 'kubernetes.io/os': 'linux'}, 'managed_fields': [{'api_version': 'v1', 'fields_type': 'FieldsV1', 'fields_v1': {'f:metadata': {'f:annotations': {'.': {}, 'f:kubeadm.alpha.kubernetes.io/cri-socket': {}, 'f:volumes.kubernetes.io/controller-managed-attach-detach': {}}, 'f:labels': {'.': {}, 'f:beta.kubernetes.io/arch': {}, 'f:beta.kubernetes.io/os': {}, 'f:kubernetes.io/arch': {}, 'f:kubernetes.io/hostname': {}, 'f:kubernetes.io/os': {}}}}, 'manager': 'Go-http-client', 'operation': 'Update', 'time': datetime.datetime(2022, 1, 20, 15, 31, 58, tzinfo=tzutc())}, {'api_version': 'v1', 'fields_type': 'FieldsV1', 'fields_v1': {'f:metadata': {'f:annotations': {'f:flannel.alpha.coreos.com/backend-data': {}, 'f:flannel.alpha.coreos.com/backend-type': {}, 'f:flannel.alpha.coreos.com/kube-subnet-manager': {}, 'f:flannel.alpha.coreos.com/public-ip': {}}}, 'f:status': {'f:conditions': {'k:{"type":"NetworkUnavailable"}': {'.': {}, 'f:lastHeartbeatTime': {}, 'f:lastTransitionTime': {}, 'f:message': {}, 'f:reason': {}, 'f:status': {}, 'f:type': {}}}}}, 'manager': 'flanneld', 'operation': 'Update', 'time': datetime.datetime(2022, 1, 20, 15, 37, 17, tzinfo=tzutc())}, {'api_version': 'v1', 'fields_type': 'FieldsV1', 'fields_v1': {'f:metadata': {'f:annotations': {'f:node.alpha.kubernetes.io/ttl': {}}}, 'f:spec': {'f:podCIDR': {}, 'f:podCIDRs': {'.': {}, 'v:"10.244.2.0/24"': {}}}}, 'manager': 'kube-controller-manager', 'operation': 'Update', 'time': datetime.datetime(2022, 2, 22, 14, 31, 52, tzinfo=tzutc())}, {'api_version': 'v1', 'fields_type': 'FieldsV1', 'fields_v1': {'f:status': {'f:allocatable': {'f:ephemeral-storage': {}}, 'f:capacity': {'f:ephemeral-storage': {}}, 'f:conditions': {'k:{"type":"DiskPressure"}': {'f:lastHeartbeatTime': {}, 'f:lastTransitionTime': {}, 'f:message': {}, 'f:reason': {}, 'f:status': {}}, 'k:{"type":"MemoryPressure"}': {'f:lastHeartbeatTime': {}, 'f:lastTransitionTime': {}, 'f:message': {}, 'f:reason': {}, 'f:status': {}}, 'k:{"type":"PIDPressure"}': {'f:lastHeartbeatTime': {}, 'f:lastTransitionTime': {}, 'f:message': {}, 'f:reason': {}, 'f:status': {}}, 'k:{"type":"Ready"}': {'f:lastHeartbeatTime': {}, 'f:lastTransitionTime': {}, 'f:message': {}, 'f:reason': {}, 'f:status': {}}}, 'f:images': {}, 'f:nodeInfo': {'f:bootID': {}}}}, 'manager': 'Go-http-client', 'operation': 'Update', 'time': datetime.datetime(2022, 2, 22, 14, 34, 51, tzinfo=tzutc())}], 'name': 'mcwk8s-node2', 'namespace': None, 'owner_references': None, 'resource_version': '8792', 'self_link': None, 'uid': '9653db01-cdfa-4378-9e3c-8d5833cf403e'}, 'spec': {'config_source': None, 'external_id': None, 'pod_cid_rs': ['10.244.2.0/24'], 'pod_cidr': '10.244.2.0/24', 'provider_id': None, 'taints': None, 'unschedulable': None}, 'status': {'addresses': [{'address': '10.0.0.6', 'type': 'InternalIP'}, {'address': 'mcwk8s-node2', 'type': 'Hostname'}], 'allocatable': {'cpu': '1', 'ephemeral-storage': '17804191305', 'hugepages-2Mi': '0', 'memory': '897296Ki', 'pods': '110'}, 'capacity': {'cpu': '1', 'ephemeral-storage': '18866Mi', 'hugepages-2Mi': '0', 'memory': '999696Ki', 'pods': '110'}, 'conditions': [{'last_heartbeat_time': datetime.datetime(2022, 2, 22, 14, 35, 12, tzinfo=tzutc()), 'last_transition_time': datetime.datetime(2022, 2, 22, 14, 35, 12, tzinfo=tzutc()), 'message': 'Flannel is running on this ' 'node', 'reason': 'FlannelIsUp', 'status': 'False', 'type': 'NetworkUnavailable'}, {'last_heartbeat_time': datetime.datetime(2022, 2, 22, 15, 46, 40, tzinfo=tzutc()), 'last_transition_time': datetime.datetime(2022, 2, 22, 14, 35, 3, tzinfo=tzutc()), 'message': 'kubelet has sufficient ' 'memory available', 'reason': 'KubeletHasSufficientMemory', 'status': 'False', 'type': 'MemoryPressure'}, {'last_heartbeat_time': datetime.datetime(2022, 2, 22, 15, 46, 40, tzinfo=tzutc()), 'last_transition_time': datetime.datetime(2022, 2, 22, 14, 35, 3, tzinfo=tzutc()), 'message': 'kubelet has no disk ' 'pressure', 'reason': 'KubeletHasNoDiskPressure', 'status': 'False', 'type': 'DiskPressure'}, {'last_heartbeat_time': datetime.datetime(2022, 2, 22, 15, 46, 40, tzinfo=tzutc()), 'last_transition_time': datetime.datetime(2022, 2, 22, 14, 35, 3, tzinfo=tzutc()), 'message': 'kubelet has sufficient PID ' 'available', 'reason': 'KubeletHasSufficientPID', 'status': 'False', 'type': 'PIDPressure'}, {'last_heartbeat_time': datetime.datetime(2022, 2, 22, 15, 46, 40, tzinfo=tzutc()), 'last_transition_time': datetime.datetime(2022, 2, 22, 14, 35, 3, tzinfo=tzutc()), 'message': 'kubelet is posting ready ' 'status', 'reason': 'KubeletReady', 'status': 'True', 'type': 'Ready'}], 'config': None, 'daemon_endpoints': {'kubelet_endpoint': {'port': 10250}}, 'images': [{'names': ['centos@sha256:a27fd8080b517143cbbbab9dfb7c8571c40d67d534bbdee55bd6c473f432b177', 'centos:latest'], 'size_bytes': 231268856}, {'names': ['kubernetesui/dashboard@sha256:1b020f566b5d65a0273c3f4ed16f37dedcb95ee2c9fa6f1c42424ec10b2fd2d7', 'kubernetesui/dashboard:v2.5.0'], 'size_bytes': 222688266}, {'names': ['registry.aliyuncs.com/google_containers/kube-proxy@sha256:ba5545c288ffd91a94a57c665355e7585c650122088bb818d06b74f2ce0c4a98', 'registry.aliyuncs.com/google_containers/kube-proxy:v1.23.2'], 'size_bytes': 112327826}, {'names': ['nginx@sha256:e3456c851a152494c3e4ff5fcc26f240206abac0c9d794affb40e0714846c451', 'nginx:1.7.9'], 'size_bytes': 91664166}, {'names': ['ghcr.io/weaveworks/launcher/scope@sha256:8591bb11d72f784f784ac8414660759d40b7c0d8819011660c1cc94271480a83', 'ghcr.io/weaveworks/launcher/scope:1.13.2'], 'size_bytes': 84949942}, {'names': ['quay.io/coreos/flannel@sha256:9a296fbb67790659adc3701e287adde3c59803b7fcefe354f1fc482840cdb3d9', 'quay.io/coreos/flannel:v0.15.1'], 'size_bytes': 69516425}, {'names': ['registry.cn-hangzhou.aliyuncs.com/google_containers/heapster-influxdb-amd64@sha256:06f3919887956ce5f5a693b96e7c54c80f54253f353fed8234da3d51dddef7e1', 'registry.cn-hangzhou.aliyuncs.com/google_containers/heapster-influxdb-amd64:v1.5.2'], 'size_bytes': 16515310}, {'names': ['rancher/mirrored-flannelcni-flannel-cni-plugin@sha256:bfe8f30c74bc6f31eba0cc6659e396dbdd5ab171314ed542cc238ae046660ede', 'rancher/mirrored-flannelcni-flannel-cni-plugin:v1.0.0'], 'size_bytes': 9031177}, {'names': ['registry.aliyuncs.com/google_containers/pause@sha256:3d380ca8864549e74af4b29c10f9cb0956236dfb01c40ca076fb6c37253234db', 'registry.aliyuncs.com/google_containers/pause:3.6'], 'size_bytes': 682696}], 'node_info': {'architecture': 'amd64', 'boot_id': '53c6412f-c917-4dae-8116-2aeb43f03d79', 'container_runtime_version': 'docker://20.10.12', 'kernel_version': '3.10.0-693.el7.x86_64', 'kube_proxy_version': 'v1.23.1', 'kubelet_version': 'v1.23.1', 'machine_id': '63e6f2e139874881a1b9e3ad51480ff3', 'operating_system': 'linux', 'os_image': 'CentOS Linux 7 (Core)', 'system_uuid': 'F7954D56-F9C7-DB96-96EA-1D2BF6EB83C3'}, 'phase': None, 'volumes_attached': None, 'volumes_in_use': None}}], 'kind': 'NodeList', 'metadata': {'_continue': None, 'remaining_item_count': None, 'resource_version': '8863', 'self_link': None}}
下面我们单拿出一个master节点来看,它包含下面的信息。有点像我们的部署配置文件结构
看下元数据中的信息
这个字段下有host ip
下面是标签
管理字段下有api版本信息
规格下有cidr,有可不可以调度
看下状态,状态有下面那些,有主机名,host ip,cpu,内存等等
有节点上的镜像信息,节点信息,这是状态字段下的
所以下面的函数是循环所有的节点,然后将每个节点的名称作为键,将节点的部分需要信息,比如节点名称,状态,版本,操作系统版本等获取出来作为值
1.3、列出所有的services
#列出所有的services def list_service(): api_response = Api_Instance.list_service_for_all_namespaces() return api_response allservice=list_service() print(allservice)
{'api_version': 'v1', 'items': [{'api_version': None, 'kind': None, 'metadata': {'annotations': None, 'cluster_name': None, 'creation_timestamp': datetime.datetime(2022, 1, 20, 15, 19, 52, tzinfo=tzutc()), 'deletion_grace_period_seconds': None, 'deletion_timestamp': None, 'finalizers': None, 'generate_name': None, 'generation': None, 'labels': {'component': 'apiserver', 'provider': 'kubernetes'}, 'managed_fields': [{'api_version': 'v1', 'fields_type': 'FieldsV1', 'fields_v1': {'f:metadata': {'f:labels': {'.': {}, 'f:component': {}, 'f:provider': {}}}, 'f:spec': {'f:clusterIP': {}, 'f:internalTrafficPolicy': {}, 'f:ipFamilyPolicy': {}, 'f:ports': {'.': {}, 'k:{"port":443,"protocol":"TCP"}': {'.': {}, 'f:name': {}, 'f:port': {}, 'f:protocol': {}, 'f:targetPort': {}}}, 'f:sessionAffinity': {}, 'f:type': {}}}, 'manager': 'kube-apiserver', 'operation': 'Update', 'time': datetime.datetime(2022, 1, 20, 15, 19, 52, tzinfo=tzutc())}], 'name': 'kubernetes', 'namespace': 'default', 'owner_references': None, 'resource_version': '213', 'self_link': None, 'uid': '7a6bb15d-e591-4ab3-b559-afb1b2ae243e'}, 'spec': {'allocate_load_balancer_node_ports': None, 'cluster_i_ps': ['10.96.0.1'], 'cluster_ip': '10.96.0.1', 'external_i_ps': None, 'external_name': None, 'external_traffic_policy': None, 'health_check_node_port': None, 'internal_traffic_policy': 'Cluster', 'ip_families': ['IPv4'], 'ip_family_policy': 'SingleStack', 'load_balancer_class': None, 'load_balancer_ip': None, 'load_balancer_source_ranges': None, 'ports': [{'app_protocol': None, 'name': 'https', 'node_port': None, 'port': 443, 'protocol': 'TCP', 'target_port': 6443}], 'publish_not_ready_addresses': None, 'selector': None, 'session_affinity': 'None', 'session_affinity_config': None, 'topology_keys': None, 'type': 'ClusterIP'}, 'status': {'conditions': None, 'load_balancer': {'ingress': None}}}, {'api_version': None, 'kind': None, 'metadata': {'annotations': {'prometheus.io/port': '9153', 'prometheus.io/scrape': 'true'}, 'cluster_name': None, 'creation_timestamp': datetime.datetime(2022, 1, 20, 15, 19, 55, tzinfo=tzutc()), 'deletion_grace_period_seconds': None, 'deletion_timestamp': None, 'finalizers': None, 'generate_name': None, 'generation': None, 'labels': {'k8s-app': 'kube-dns', 'kubernetes.io/cluster-service': 'true', 'kubernetes.io/name': 'CoreDNS'}, 'managed_fields': [{'api_version': 'v1', 'fields_type': 'FieldsV1', 'fields_v1': {'f:metadata': {'f:annotations': {'.': {}, 'f:prometheus.io/port': {}, 'f:prometheus.io/scrape': {}}, 'f:labels': {'.': {}, 'f:k8s-app': {}, 'f:kubernetes.io/cluster-service': {}, 'f:kubernetes.io/name': {}}}, 'f:spec': {'f:clusterIP': {}, 'f:internalTrafficPolicy': {}, 'f:ports': {'.': {}, 'k:{"port":53,"protocol":"TCP"}': {'.': {}, 'f:name': {}, 'f:port': {}, 'f:protocol': {}, 'f:targetPort': {}}, 'k:{"port":53,"protocol":"UDP"}': {'.': {}, 'f:name': {}, 'f:port': {}, 'f:protocol': {}, 'f:targetPort': {}}, 'k:{"port":9153,"protocol":"TCP"}': {'.': {}, 'f:name': {}, 'f:port': {}, 'f:protocol': {}, 'f:targetPort': {}}}, 'f:selector': {}, 'f:sessionAffinity': {}, 'f:type': {}}}, 'manager': 'Go-http-client', 'operation': 'Update', 'time': datetime.datetime(2022, 1, 20, 15, 19, 55, tzinfo=tzutc())}], 'name': 'kube-dns', 'namespace': 'kube-system', 'owner_references': None, 'resource_version': '264', 'self_link': None, 'uid': '666ead5f-3422-410b-b524-fb56eb418c39'}, 'spec': {'allocate_load_balancer_node_ports': None, 'cluster_i_ps': ['10.96.0.10'], 'cluster_ip': '10.96.0.10', 'external_i_ps': None, 'external_name': None, 'external_traffic_policy': None, 'health_check_node_port': None, 'internal_traffic_policy': 'Cluster', 'ip_families': ['IPv4'], 'ip_family_policy': 'SingleStack', 'load_balancer_class': None, 'load_balancer_ip': None, 'load_balancer_source_ranges': None, 'ports': [{'app_protocol': None, 'name': 'dns', 'node_port': None, 'port': 53, 'protocol': 'UDP', 'target_port': 53}, {'app_protocol': None, 'name': 'dns-tcp', 'node_port': None, 'port': 53, 'protocol': 'TCP', 'target_port': 53}, {'app_protocol': None, 'name': 'metrics', 'node_port': None, 'port': 9153, 'protocol': 'TCP', 'target_port': 9153}], 'publish_not_ready_addresses': None, 'selector': {'k8s-app': 'kube-dns'}, 'session_affinity': 'None', 'session_affinity_config': None, 'topology_keys': None, 'type': 'ClusterIP'}, 'status': {'conditions': None, 'load_balancer': {'ingress': None}}}], 'kind': 'ServiceList', 'metadata': {'_continue': None, 'remaining_item_count': None, 'resource_version': '15796', 'self_link': None}}
响应信息和前面的结构一样,想要啥自己再查一下获取。
1.4、列出所有的pod
#列出所有的pod def list_pod(): api_response = 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 allPod=list_pod() print(allPod)
{ 'coredns-6d8c4cb4d-vctxx': { 'ip': '10.244.0.2', 'namespace': 'kube-system' }, 'coredns-6d8c4cb4d-xkv9h': { 'ip': '10.244.0.3', 'namespace': 'kube-system' }, 'etcd-mcwk8s-master': { 'ip': '10.0.0.4', 'namespace': 'kube-system' }, 'kube-apiserver-mcwk8s-master': { 'ip': '10.0.0.4', 'namespace': 'kube-system' }, 'kube-controller-manager-mcwk8s-master': { 'ip': '10.0.0.4', 'namespace': 'kube-system' }, 'kube-flannel-ds-fvwgm': { 'ip': '10.0.0.5', 'namespace': 'kube-system' }, 'kube-flannel-ds-l5fdg': { 'ip': '10.0.0.4', 'namespace': 'kube-system' }, 'kube-flannel-ds-mzdcw': { 'ip': '10.0.0.6', 'namespace': 'kube-system' }, 'kube-proxy-796l7': { 'ip': '10.0.0.6', 'namespace': 'kube-system' }, 'kube-proxy-8wtxn': { 'ip': '10.0.0.5', 'namespace': 'kube-system' }, 'kube-proxy-qr6b8': { 'ip': '10.0.0.4', 'namespace': 'kube-system' }, 'kube-scheduler-mcwk8s-master': { 'ip': '10.0.0.4', 'namespace': 'kube-system' } }
上面函数只取了pod名称。ip,命名空间
下面打印一下所有pod返回的原始数据,结构同前,自己找需要的信息
api_response = Api_Instance.list_pod_for_all_namespaces()
print(api_response)
{'api_version': 'v1', 'items': [{'api_version': None, 'kind': None, 'metadata': {'annotations': None, 'cluster_name': None, 'creation_timestamp': datetime.datetime(2022, 1, 20, 15, 20, 9, tzinfo=tzutc()), 'deletion_grace_period_seconds': None, 'deletion_timestamp': None, 'finalizers': None, 'generate_name': 'coredns-6d8c4cb4d-', 'generation': None, 'labels': {'k8s-app': 'kube-dns', 'pod-template-hash': '6d8c4cb4d'}, 'managed_fields': [{'api_version': 'v1', 'fields_type': 'FieldsV1', 'fields_v1': {'f:metadata': {'f:generateName': {}, 'f:labels': {'.': {}, 'f:k8s-app': {}, 'f:pod-template-hash': {}}, 'f:ownerReferences': {'.': {}, 'k:{"uid":"d92eb89e-cf9a-4b42-892c-db58238a7cc3"}': {}}}, 'f:spec': {'f:containers': {'k:{"name":"coredns"}': {'.': {}, 'f:args': {}, 'f:image': {}, 'f:imagePullPolicy': {}, 'f:livenessProbe': {'.': {}, 'f:failureThreshold': {}, 'f:httpGet': {'.': {}, 'f:path': {}, 'f:port': {}, 'f:scheme': {}}, 'f:initialDelaySeconds': {}, 'f:periodSeconds': {}, 'f:successThreshold': {}, 'f:timeoutSeconds': {}}, 'f:name': {}, 'f:ports': {'.': {}, 'k:{"containerPort":53,"protocol":"TCP"}': {'.': {}, 'f:containerPort': {}, 'f:name': {}, 'f:protocol': {}}, 'k:{"containerPort":53,"protocol":"UDP"}': {'.': {}, 'f:containerPort': {}, 'f:name': {}, 'f:protocol': {}}, 'k:{"containerPort":9153,"protocol":"TCP"}': {'.': {}, 'f:containerPort': {}, 'f:name': {}, 'f:protocol': {}}}, 'f:readinessProbe': {'.': {}, 'f:failureThreshold': {}, 'f:httpGet': {'.': {}, 'f:path': {}, 'f:port': {}, 'f:scheme': {}}, 'f:periodSeconds': {}, 'f:successThreshold': {}, 'f:timeoutSeconds': {}}, 'f:resources': {'.': {}, 'f:limits': {'.': {}, 'f:memory': {}}, 'f:requests': {'.': {}, 'f:cpu': {}, 'f:memory': {}}}, 'f:securityContext': {'.': {}, 'f:allowPrivilegeEscalation': {}, 'f:capabilities': {'.': {}, 'f:add': {}, 'f:drop': {}}, 'f:readOnlyRootFilesystem': {}}, 'f:terminationMessagePath': {}, 'f:terminationMessagePolicy': {}, 'f:volumeMounts': {'.': {}, 'k:{"mountPath":"/etc/coredns"}': {'.': {}, 'f:mountPath': {}, 'f:name': {}, 'f:readOnly': {}}}}}, 'f:dnsPolicy': {}, 'f:enableServiceLinks': {}, 'f:nodeSelector': {}, 'f:priorityClassName': {}, 'f:restartPolicy': {}, 'f:schedulerName': {}, 'f:securityContext': {}, 'f:serviceAccount': {}, 'f:serviceAccountName': {}, 'f:terminationGracePeriodSeconds': {}, 'f:tolerations': {}, 'f:volumes': {'.': {}, 'k:{"name":"config-volume"}': {'.': {}, 'f:configMap': {'.': {}, 'f:defaultMode': {}, 'f:items': {}, 'f:name': {}}, 'f:name': {}}}}}, 'manager': 'kube-controller-manager', 'operation': 'Update', 'time': datetime.datetime(2022, 1, 20, 15, 20, 9, tzinfo=tzutc())}, {'api_version': 'v1', 'fields_type': 'FieldsV1', 'fields_v1': {'f:status': {'f:conditions': {'.': {}, 'k:{"type":"PodScheduled"}': {'.': {}, 'f:lastProbeTime': {}, 'f:lastTransitionTime': {}, 'f:message': {}, 'f:reason': {}, 'f:status': {}, 'f:type': {}}}}}, 'manager': 'kube-scheduler', 'operation': 'Update', 'time': datetime.datetime(2022, 1, 20, 15, 20, 9, tzinfo=tzutc())}, {'api_version': 'v1', 'fields_type': 'FieldsV1', 'fields_v1': {'f:status': {'f:conditions': {'k:{"type":"ContainersReady"}': {'.': {}, 'f:lastProbeTime': {}, 'f:lastTransitionTime': {}, 'f:status': {}, 'f:type': {}}, 'k:{"type":"Initialized"}': {'.': {}, 'f:lastProbeTime': {}, 'f:lastTransitionTime': {}, 'f:status': {}, 'f:type': {}}, 'k:{"type":"Ready"}': {'.': {}, 'f:lastProbeTime': {}, 'f:lastTransitionTime': {}, 'f:status': {}, 'f:type': {}}}, 'f:containerStatuses': {}, 'f:hostIP': {}, 'f:phase': {}, 'f:podIP': {}, 'f:podIPs': {'.': {}, 'k:{"ip":"10.244.0.2"}': {'.': {}, 'f:ip': {}}}, 'f:startTime': {}}}, 'manager': 'Go-http-client', 'operation': 'Update', 'time': datetime.datetime(2022, 1, 20, 15, 30, 47, tzinfo=tzutc())}], 'name': 'coredns-6d8c4cb4d-vctxx', 'namespace': 'kube-system', 'owner_references': [{'api_version': 'apps/v1', 'block_owner_deletion': True, 'controller': True, 'kind': 'ReplicaSet', 'name': 'coredns-6d8c4cb4d', 'uid': 'd92eb89e-cf9a-4b42-892c-db58238a7cc3'}], 'resource_version': '1285', 'self_link': None, 'uid': 'a1acc7cf-f3bb-40ec-b76a-437ff38cdd10'}, 'spec': {'active_deadline_seconds': None, 'affinity': None, 'automount_service_account_token': None, 'containers': [{'args': ['-conf', '/etc/coredns/Corefile'], 'command': None, 'env': None, 'env_from': None, 'image': 'registry.aliyuncs.com/google_containers/coredns:v1.8.6', 'image_pull_policy': 'IfNotPresent', 'lifecycle': None, 'liveness_probe': {'_exec': None, 'failure_threshold': 5, 'http_get': {'host': None, 'http_headers': None, 'path': '/health', 'port': 8080, 'scheme': 'HTTP'}, 'initial_delay_seconds': 60, 'period_seconds': 10, 'success_threshold': 1, 'tcp_socket': None, 'termination_grace_period_seconds': None, 'timeout_seconds': 5}, 'name': 'coredns', 'ports': [{'container_port': 53, 'host_ip': None, 'host_port': None, 'name': 'dns', 'protocol': 'UDP'}, {'container_port': 53, 'host_ip': None, 'host_port': None, 'name': 'dns-tcp', 'protocol': 'TCP'}, {'container_port': 9153, 'host_ip': None, 'host_port': None, 'name': 'metrics', 'protocol': 'TCP'}], 'readiness_probe': {'_exec': None, 'failure_threshold': 3, 'http_get': {'host': None, 'http_headers': None, 'path': '/ready', 'port': 8181, 'scheme': 'HTTP'}, 'initial_delay_seconds': None, 'period_seconds': 10, 'success_threshold': 1, 'tcp_socket': None, 'termination_grace_period_seconds': None, 'timeout_seconds': 1}, 'resources': {'limits': {'memory': '170Mi'}, 'requests': {'cpu': '100m', 'memory': '70Mi'}}, 'security_context': {'allow_privilege_escalation': False, 'capabilities': {'add': ['NET_BIND_SERVICE'], 'drop': ['all']}, 'privileged': None, 'proc_mount': None, 'read_only_root_filesystem': True, 'run_as_group': None, 'run_as_non_root': None, 'run_as_user': None, 'se_linux_options': None, 'seccomp_profile': None, 'windows_options': None}, 'startup_probe': None, 'stdin': None, 'stdin_once': None, 'termination_message_path': '/dev/termination-log', 'termination_message_policy': 'File', 'tty': None, 'volume_devices': None, 'volume_mounts': [{'mount_path': '/etc/coredns', 'mount_propagation': None, 'name': 'config-volume', 'read_only': True, 'sub_path': None, 'sub_path_expr': None}, {'mount_path': '/var/run/secrets/kubernetes.io/serviceaccount', 'mount_propagation': None, 'name': 'kube-api-access-wwl9w', 'read_only': True, 'sub_path': None, 'sub_path_expr': None}], 'working_dir': None}], 'dns_config': None, 'dns_policy': 'Default', 'enable_service_links': True, 'ephemeral_containers': None, 'host_aliases': None, 'host_ipc': None, 'host_network': None, 'host_pid': None, 'hostname': None, 'image_pull_secrets': None, 'init_containers': None, 'node_name': 'mcwk8s-master', 'node_selector': {'kubernetes.io/os': 'linux'}, 'overhead': None, 'preemption_policy': 'PreemptLowerPriority', 'priority': 2000000000, 'priority_class_name': 'system-cluster-critical', 'readiness_gates': None, 'restart_policy': 'Always', 'runtime_class_name': None, 'scheduler_name': 'default-scheduler', 'security_context': {'fs_group': None, 'fs_group_change_policy': None, 'run_as_group': None, 'run_as_non_root': None, 'run_as_user': None, 'se_linux_options': None, 'seccomp_profile': None, 'supplemental_groups': None, 'sysctls': None, 'windows_options': None}, 'service_account': 'coredns', 'service_account_name': 'coredns', 'set_hostname_as_fqdn': None, 'share_process_namespace': None, 'subdomain': None, 'termination_grace_period_seconds': 30, 'tolerations': [{'effect': None, 'key': 'CriticalAddonsOnly', 'operator': 'Exists', 'toleration_seconds': None, 'value': None}, {'effect': 'NoSchedule', 'key': 'node-role.kubernetes.io/master', 'operator': None, 'toleration_seconds': None, 'value': None}, {'effect': 'NoSchedule', 'key': 'node-role.kubernetes.io/control-plane', 'operator': None, 'toleration_seconds': None, 'value': None}, {'effect': 'NoExecute', 'key': 'node.kubernetes.io/not-ready', 'operator': 'Exists', 'toleration_seconds': 300, 'value': None}, {'effect': 'NoExecute', 'key': 'node.kubernetes.io/unreachable', 'operator': 'Exists', 'toleration_seconds': 300, 'value': None}], 'topology_spread_constraints': None, 'volumes': [{'aws_elastic_block_store': None, 'azure_disk': None, 'azure_file': None, 'cephfs': None, 'cinder': None, 'config_map': {'default_mode': 420, 'items': [{'key': 'Corefile', 'mode': None, 'path': 'Corefile'}], 'name': 'coredns', 'optional': None}, 'csi': None, 'downward_api': None, 'empty_dir': None, 'ephemeral': None, 'fc': None, 'flex_volume': None, 'flocker': None, 'gce_persistent_disk': None, 'git_repo': None, 'glusterfs': None, 'host_path': None, 'iscsi': None, 'name': 'config-volume', 'nfs': None, 'persistent_volume_claim': None, 'photon_persistent_disk': None, 'portworx_volume': None, 'projected': None, 'quobyte': None, 'rbd': None, 'scale_io': None, 'secret': None, 'storageos': None, 'vsphere_volume': None}, {'aws_elastic_block_store': None, 'azure_disk': None, 'azure_file': None, 'cephfs': None, 'cinder': None, 'config_map': None, 'csi': None, 'downward_api': None, 'empty_dir': None, 'ephemeral': None, 'fc': None, 'flex_volume': None, 'flocker': None, 'gce_persistent_disk': None, 'git_repo': None, 'glusterfs': None, 'host_path': None, 'iscsi': None, 'name': 'kube-api-access-wwl9w', 'nfs': None, 'persistent_volume_claim': None, 'photon_persistent_disk': None, 'portworx_volume': None, 'projected': {'default_mode': 420, 'sources': [{'config_map': None, 'downward_api': None, 'secret': None, 'service_account_token': {'audience': None, 'expiration_seconds': 3607, 'path': 'token'}}, {'config_map': {'items': [{'key': 'ca.crt', 'mode': None, 'path': 'ca.crt'}], 'name': 'kube-root-ca.crt', 'optional': None}, 'downward_api': None, 'secret': None, 'service_account_token': None}, {'config_map': None, 'downward_api': {'items': [{'field_ref': {'api_version': 'v1', 'field_path': 'metadata.namespace'}, 'mode': None, 'path': 'namespace', 'resource_field_ref': None}]}, 'secret': None, 'service_account_token': None}]}, 'quobyte': None, 'rbd': None, 'scale_io': None, 'secret': None, 'storageos': None, 'vsphere_volume': None}]}, 'status': {'conditions': [{'last_probe_time': None, 'last_transition_time': datetime.datetime(2022, 1, 20, 15, 30, 45, tzinfo=tzutc()), 'message': None, 'reason': None, 'status': 'True', 'type': 'Initialized'}, {'last_probe_time': None, 'last_transition_time': datetime.datetime(2022, 1, 20, 15, 30, 47, tzinfo=tzutc()), 'message': None, 'reason': None, 'status': 'True', 'type': 'Ready'}, {'last_probe_time': None, 'last_transition_time': datetime.datetime(2022, 1, 20, 15, 30, 47, tzinfo=tzutc()), 'message': None, 'reason': None, 'status': 'True', 'type': 'ContainersReady'}, {'last_probe_time': None, 'last_transition_time': datetime.datetime(2022, 1, 20, 15, 30, 45, tzinfo=tzutc()), 'message': None, 'reason': None, 'status': 'True', 'type': 'PodScheduled'}], 'container_statuses': [{'container_id': 'docker://3212345b369913f77e45fa3c6334b2a3dc487da8bf79e3b9b8148189d63ccb77', 'image': 'registry.aliyuncs.com/google_containers/coredns:v1.8.6', 'image_id': 'docker-pullable://registry.aliyuncs.com/google_containers/coredns@sha256:5b6ec0d6de9baaf3e92d0f66cd96a25b9edbce8716f5f15dcd1a616b3abd590e', 'last_state': {'running': None, 'terminated': None, 'waiting': None}, 'name': 'coredns', 'ready': True, 'restart_count': 0, 'started': True, 'state': {'running': {'started_at': datetime.datetime(2022, 1, 20, 15, 30, 47, tzinfo=tzutc())}, 'terminated': None, 'waiting': None}}], 'ephemeral_container_statuses': None, 'host_ip': '10.0.0.4', 'init_container_statuses': None, 'message': None, 'nominated_node_name': None, 'phase': 'Running', 'pod_i_ps': [{'ip': '10.244.0.2'}], 'pod_ip': '10.244.0.2', 'qos_class': 'Burstable', 'reason': None, 'start_time': datetime.datetime(2022, 1, 20, 15, 30, 45, tzinfo=tzutc())}}, ......] 'kind': 'PodList', 'metadata': {'_continue': None, 'remaining_item_count': None, 'resource_version': '16884', 'self_link': None}}
数据量有点大
1.4、列出所有job
#列出所有job def list_job_for_all_namespaces(): api_response = Api_Batch.list_job_for_all_namespaces() return api_response allJob=list_job_for_all_namespaces() print(allJob)
{'api_version': 'batch/v1', 'items': [], 'kind': 'JobList', 'metadata': {'_continue': None, 'remaining_item_count': None, 'resource_version': '18321', 'self_link': None}}
1.5、列出指定命名空间的job
def list_job(namespace="default"): api_response = Api_Batch.list_namespaced_job(namespace) return api_response listJob=list_job() print(listJob)
{'api_version': 'batch/v1', 'items': [], 'kind': 'JobList', 'metadata': {'_continue': None, 'remaining_item_count': None, 'resource_version': '18555', 'self_link': None}}
1.6、各个指定命名空间的资源查询方法
如下,只列出default下面的所有服务
def list_service(namespace="default"): api_response = Api_Instance.list_namespaced_service(namespace) return api_response listService=list_service() print(listService)
这个命名空间下只有这一个
2、创建k8s资源对象
2.1、创建pod
文件来源:https://www.cnblogs.com/machangwei-8/p/15851696.html
目前没有pod,返回的是这个pod的信息。
pod已经创建出来,但是由于我们部署配置文件里面设置了退出容器的命令了,所以有错误
我们将部署配置文件的;exit 1删除,重新执行部署函数
当重新执行函数的时候表示pod已经存在了
Reason: Conflict
HTTP response headers: HTTPHeaderDict({'Audit-Id': 'e0813d1a-580d-4ca0-acb8-ca40ddc75d0b', 'Cache-Control': 'no-cache, private', 'Content-Type': 'application/json', 'X-Kubernetes-Pf-Flowschema-Uid': '97b2a71d-4489-4de6-9e98-d2fbd1821053', 'X-Kubernetes-Pf-Prioritylevel-Uid': '2b5cc6c7-7292-4961-9864-4b8f183f7e7d', 'Date': 'Wed, 23 Feb 2022 02:09:56 GMT', 'Content-Length': '208'})
HTTP response body: {"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"pods \"mcw-healthcheck\" already exists","reason":"AlreadyExists","details":{"name":"mcw-healthcheck","kind":"pods"},"code":409}
那么删除pod再操作,就已经好了,成功创建
2.2、创建service
# 创建service def create_service(file, namespace="default"): with open(file) as f: dep = yaml.safe_load(f) api_response = Api_Instance.create_namespaced_service(namespace, body=dep) return api_response
2.3、创建job
# 创建job def create_job(file, namespace="default"): with open(file) as f: dep = yaml.safe_load(f) api_response = Api_Batch.create_namespaced_job(namespace, body=dep) return api_response
2.4、创建其它资源
其它的一样的操作,就是换个方法,用的都是这两个api对象
3、删除资源
3.1、删除pod
# 删除pod def delete_pod(name, namespace="default"): api_response = Api_Instance.delete_namespaced_pod(name, namespace) return api_response res=delete_pod("mcw-healthcheck",namespace="default") print("res:",res)
删除之前
执行删除之后,返回的结果res还是那种结构数据
3.2、删除service
# 删除service def delete_service(name, namespace="default"): api_response = Api_Instance.delete_namespaced_service(name, namespace) return api_response
3.3、删除job
# 删除job def delete_job(name, namespace="default"): api_response = Api_Batch.delete_namespaced_job(name, namespace) return api_response
3.4、删除其它资源
其它资源都是调用这两个api对象,改下方法就行
4、查看指定资源
4.1、查看指定pod的资源信息
# 查看pod def read_pod(name, namespace="default"): # 可获得:status.pod_ip api_response = Api_Instance.read_namespaced_pod(name, namespace) return api_response api_response=read_pod("kube-apiserver-mcwk8s-master",namespace="kube-system") #指定信息 print(api_response.spec.containers[0].image) #pod的镜像名 print(api_response.status.pod_ip) #pod所在的node ip
print(api_response),打印返回结果,不取值,显示是这个pod的所有信息。想要啥自己找。缩减后可以看到,pod的名称,host ip 这两个常见信息
{ 'api_version': 'v1', 'kind': 'Pod', 'metadata': { 'annotations': { 'kubeadm.kubernetes.io/kube-apiserver.advertise-address.endpoint': '10.0.0.4:6443', 'kubernetes.io/config.hash': 'dff1699661465e190e7c09219322e1b3', 'kubernetes.io/config.mirror': 'dff1699661465e190e7c09219322e1b3', 'kubernetes.io/config.seen': '2022-01-20T23:19:55.615232558+08:00', 'kubernetes.io/config.source': 'file', 'seccomp.security.alpha.kubernetes.io/pod': 'runtime/default' }, 'cluster_name': None, 'creation_timestamp': datetime.datetime(2022, 1, 20, 15, 19, 56, tzinfo=tzutc()), 'deletion_grace_period_seconds': None, 'deletion_timestamp': None, 'finalizers': None, 'generate_name': None, 'generation': None, 'labels': { 'component': 'kube-apiserver', 'tier': 'control-plane' }, 'managed_fields': [ { 'api_version': 'v1', 'fields_type': 'FieldsV1', 'fields_v1': { 'f:metadata': { 'f:annotations': { '.': {}, 'f:kubeadm.kubernetes.io/kube-apiserver.advertise-address.endpoint': {}, 'f:kubernetes.io/config.hash': {}, 'f:kubernetes.io/config.mirror': {}, 'f:kubernetes.io/config.seen': {}, 'f:kubernetes.io/config.source': {} }, 'f:labels': { '.': {}, 'f:component': {}, 'f:tier': {} }, 'f:ownerReferences': { '.': {}, 'k:{"uid":"48fad458-0655-4794-8689-b0afca67cefa"}': {} } }, 'f:spec': { 'f:containers': { 'k:{"name":"kube-apiserver"}': { '.': {}, 'f:command': {}, 'f:image': {}, 'f:imagePullPolicy': {}, 'f:livenessProbe': { '.': {}, 'f:failureThreshold': {}, 'f:httpGet': { '.': {}, 'f:host': {}, 'f:path': {}, 'f:port': {}, 'f:scheme': {} }, 'f:initialDelaySeconds': {}, 'f:periodSeconds': {}, 'f:successThreshold': {}, 'f:timeoutSeconds': {} }, 'f:name': {}, 'f:readinessProbe': { '.': {}, 'f:failureThreshold': {}, 'f:httpGet': { '.': {}, 'f:host': {}, 'f:path': {}, 'f:port': {}, 'f:scheme': {} }, 'f:periodSeconds': {}, 'f:successThreshold': {}, 'f:timeoutSeconds': {} }, 'f:resources': { '.': {}, 'f:requests': { '.': {}, 'f:cpu': {} } }, 'f:startupProbe': { '.': {}, 'f:failureThreshold': {}, 'f:httpGet': { '.': {}, 'f:host': {}, 'f:path': {}, 'f:port': {}, 'f:scheme': {} }, 'f:initialDelaySeconds': {}, 'f:periodSeconds': {}, 'f:successThreshold': {}, 'f:timeoutSeconds': {} }, 'f:terminationMessagePath': {}, 'f:terminationMessagePolicy': {}, 'f:volumeMounts': { '.': {}, 'k:{"mountPath":"/etc/kubernetes/pki"}': { '.': {}, 'f:mountPath': {}, 'f:name': {}, 'f:readOnly': {} }, 'k:{"mountPath":"/etc/pki"}': { '.': {}, 'f:mountPath': {}, 'f:name': {}, 'f:readOnly': {} }, 'k:{"mountPath":"/etc/ssl/certs"}': { '.': {}, 'f:mountPath': {}, 'f:name': {}, 'f:readOnly': {} } } } }, 'f:dnsPolicy': {}, 'f:enableServiceLinks': {}, 'f:hostNetwork': {}, 'f:nodeName': {}, 'f:priorityClassName': {}, 'f:restartPolicy': {}, 'f:schedulerName': {}, 'f:securityContext': { '.': {}, 'f:seccompProfile': { '.': {}, 'f:type': {} } }, 'f:terminationGracePeriodSeconds': {}, 'f:tolerations': {}, 'f:volumes': { '.': {}, 'k:{"name":"ca-certs"}': { '.': {}, 'f:hostPath': { '.': {}, 'f:path': {}, 'f:type': {} }, 'f:name': {} }, 'k:{"name":"etc-pki"}': { '.': {}, 'f:hostPath': { '.': {}, 'f:path': {}, 'f:type': {} }, 'f:name': {} }, 'k:{"name":"k8s-certs"}': { '.': {}, 'f:hostPath': { '.': {}, 'f:path': {}, 'f:type': {} }, 'f:name': {} } } } }, 'manager': 'Go-http-client', 'operation': 'Update', 'time': datetime.datetime(2022, 1, 20, 15, 19, 56, tzinfo=tzutc()) }, { 'api_version': 'v1', 'fields_type': 'FieldsV1', 'fields_v1': { 'f:status': { 'f:conditions': { '.': {}, 'k:{"type":"ContainersReady"}': { '.': {}, 'f:lastProbeTime': {}, 'f:lastTransitionTime': {}, 'f:status': {}, 'f:type': {} }, 'k:{"type":"Initialized"}': { '.': {}, 'f:lastProbeTime': {}, 'f:lastTransitionTime': {}, 'f:status': {}, 'f:type': {} }, 'k:{"type":"PodScheduled"}': { '.': {}, 'f:lastProbeTime': {}, 'f:lastTransitionTime': {}, 'f:status': {}, 'f:type': {} }, 'k:{"type":"Ready"}': { '.': {}, 'f:lastProbeTime': {}, 'f:lastTransitionTime': {}, 'f:status': {}, 'f:type': {} } }, 'f:containerStatuses': {}, 'f:hostIP': {}, 'f:phase': {}, 'f:podIP': {}, 'f:podIPs': { '.': {}, 'k:{"ip":"10.0.0.4"}': { '.': {}, 'f:ip': {} } }, 'f:startTime': {} } }, 'manager': 'Go-http-client', 'operation': 'Update', 'time': datetime.datetime(2022, 2, 22, 18, 32, 58, tzinfo=tzutc()) } ], 'name': 'kube-apiserver-mcwk8s-master', 'namespace': 'kube-system', 'owner_references': [ { 'api_version': 'v1', 'block_owner_deletion': None, 'controller': True, 'kind': 'Node', 'name': 'mcwk8s-master', 'uid': '48fad458-0655-4794-8689-b0afca67cefa' } ], 'resource_version': '20446', 'self_link': None, 'uid': 'fba19714-c584-43be-86e9-82eee8f2e518' }, 'spec': { 'active_deadline_seconds': None, 'affinity': None, 'automount_service_account_token': None, 'containers': [ { 'args': None, 'command': [ 'kube-apiserver', '--advertise-address=10.0.0.4', '--allow-privileged=true', '--authorization-mode=Node,RBAC', '--client-ca-file=/etc/kubernetes/pki/ca.crt', '--enable-admission-plugins=NodeRestriction', '--enable-bootstrap-token-auth=true', '--etcd-cafile=/etc/kubernetes/pki/etcd/ca.crt', '--etcd-certfile=/etc/kubernetes/pki/apiserver-etcd-client.crt', '--etcd-keyfile=/etc/kubernetes/pki/apiserver-etcd-client.key', '--etcd-servers=https://127.0.0.1:2379', '--kubelet-client-certificate=/etc/kubernetes/pki/apiserver-kubelet-client.crt', '--kubelet-client-key=/etc/kubernetes/pki/apiserver-kubelet-client.key', '--kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname', '--proxy-client-cert-file=/etc/kubernetes/pki/front-proxy-client.crt', '--proxy-client-key-file=/etc/kubernetes/pki/front-proxy-client.key', '--requestheader-allowed-names=front-proxy-client', '--requestheader-client-ca-file=/etc/kubernetes/pki/front-proxy-ca.crt', '--requestheader-extra-headers-prefix=X-Remote-Extra-', '--requestheader-group-headers=X-Remote-Group', '--requestheader-username-headers=X-Remote-User', '--secure-port=6443', '--service-account-issuer=https://kubernetes.default.svc.cluster.local', '--service-account-key-file=/etc/kubernetes/pki/sa.pub', '--service-account-signing-key-file=/etc/kubernetes/pki/sa.key', '--service-cluster-ip-range=10.96.0.0/12', '--tls-cert-file=/etc/kubernetes/pki/apiserver.crt', '--tls-private-key-file=/etc/kubernetes/pki/apiserver.key' ], 'env': None, 'env_from': None, 'image': 'registry.aliyuncs.com/google_containers/kube-apiserver:v1.23.2', 'image_pull_policy': 'IfNotPresent', 'lifecycle': None, 'liveness_probe': { '_exec': None, 'failure_threshold': 8, 'http_get': { 'host': '10.0.0.4', 'http_headers': None, 'path': '/livez', 'port': 6443, 'scheme': 'HTTPS' }, 'initial_delay_seconds': 10, 'period_seconds': 10, 'success_threshold': 1, 'tcp_socket': None, 'termination_grace_period_seconds': None, 'timeout_seconds': 15 }, 'name': 'kube-apiserver', 'ports': None, 'readiness_probe': { '_exec': None, 'failure_threshold': 3, 'http_get': { 'host': '10.0.0.4', 'http_headers': None, 'path': '/readyz', 'port': 6443, 'scheme': 'HTTPS' }, 'initial_delay_seconds': None, 'period_seconds': 1, 'success_threshold': 1, 'tcp_socket': None, 'termination_grace_period_seconds': None, 'timeout_seconds': 15 }, 'resources': { 'limits': None, 'requests': { 'cpu': '250m' } }, 'security_context': None, 'startup_probe': { '_exec': None, 'failure_threshold': 24, 'http_get': { 'host': '10.0.0.4', 'http_headers': None, 'path': '/livez', 'port': 6443, 'scheme': 'HTTPS' }, 'initial_delay_seconds': 10, 'period_seconds': 10, 'success_threshold': 1, 'tcp_socket': None, 'termination_grace_period_seconds': None, 'timeout_seconds': 15 }, 'stdin': None, 'stdin_once': None, 'termination_message_path': '/dev/termination-log', 'termination_message_policy': 'File', 'tty': None, 'volume_devices': None, 'volume_mounts': [ { 'mount_path': '/etc/ssl/certs', 'mount_propagation': None, 'name': 'ca-certs', 'read_only': True, 'sub_path': None, 'sub_path_expr': None }, { 'mount_path': '/etc/pki', 'mount_propagation': None, 'name': 'etc-pki', 'read_only': True, 'sub_path': None, 'sub_path_expr': None }, { 'mount_path': '/etc/kubernetes/pki', 'mount_propagation': None, 'name': 'k8s-certs', 'read_only': True, 'sub_path': None, 'sub_path_expr': None } ], 'working_dir': None } ], 'dns_config': None, 'dns_policy': 'ClusterFirst', 'enable_service_links': True, 'ephemeral_containers': None, 'host_aliases': None, 'host_ipc': None, 'host_network': True, 'host_pid': None, 'hostname': None, 'image_pull_secrets': None, 'init_containers': None, 'node_name': 'mcwk8s-master', 'node_selector': None, 'overhead': None, 'preemption_policy': 'PreemptLowerPriority', 'priority': 2000001000, 'priority_class_name': 'system-node-critical', 'readiness_gates': None, 'restart_policy': 'Always', 'runtime_class_name': None, 'scheduler_name': 'default-scheduler', 'security_context': { 'fs_group': None, 'fs_group_change_policy': None, 'run_as_group': None, 'run_as_non_root': None, 'run_as_user': None, 'se_linux_options': None, 'seccomp_profile': { 'localhost_profile': None, 'type': 'RuntimeDefault' }, 'supplemental_groups': None, 'sysctls': None, 'windows_options': None }, 'service_account': None, 'service_account_name': None, 'set_hostname_as_fqdn': None, 'share_process_namespace': None, 'subdomain': None, 'termination_grace_period_seconds': 30, 'tolerations': [ { 'effect': 'NoExecute', 'key': None, 'operator': 'Exists', 'toleration_seconds': None, 'value': None } ], 'topology_spread_constraints': None, 'volumes': [ { 'aws_elastic_block_store': None, 'azure_disk': None, 'azure_file': None, 'cephfs': None, 'cinder': None, 'config_map': None, 'csi': None, 'downward_api': None, 'empty_dir': None, 'ephemeral': None, 'fc': None, 'flex_volume': None, 'flocker': None, 'gce_persistent_disk': None, 'git_repo': None, 'glusterfs': None, 'host_path': { 'path': '/etc/ssl/certs', 'type': 'DirectoryOrCreate' }, 'iscsi': None, 'name': 'ca-certs', 'nfs': None, 'persistent_volume_claim': None, 'photon_persistent_disk': None, 'portworx_volume': None, 'projected': None, 'quobyte': None, 'rbd': None, 'scale_io': None, 'secret': None, 'storageos': None, 'vsphere_volume': None }, { 'aws_elastic_block_store': None, 'azure_disk': None, 'azure_file': None, 'cephfs': None, 'cinder': None, 'config_map': None, 'csi': None, 'downward_api': None, 'empty_dir': None, 'ephemeral': None, 'fc': None, 'flex_volume': None, 'flocker': None, 'gce_persistent_disk': None, 'git_repo': None, 'glusterfs': None, 'host_path': { 'path': '/etc/pki', 'type': 'DirectoryOrCreate' }, 'iscsi': None, 'name': 'etc-pki', 'nfs': None, 'persistent_volume_claim': None, 'photon_persistent_disk': None, 'portworx_volume': None, 'projected': None, 'quobyte': None, 'rbd': None, 'scale_io': None, 'secret': None, 'storageos': None, 'vsphere_volume': None }, { 'aws_elastic_block_store': None, 'azure_disk': None, 'azure_file': None, 'cephfs': None, 'cinder': None, 'config_map': None, 'csi': None, 'downward_api': None, 'empty_dir': None, 'ephemeral': None, 'fc': None, 'flex_volume': None, 'flocker': None, 'gce_persistent_disk': None, 'git_repo': None, 'glusterfs': None, 'host_path': { 'path': '/etc/kubernetes/pki', 'type': 'DirectoryOrCreate' }, 'iscsi': None, 'name': 'k8s-certs', 'nfs': None, 'persistent_volume_claim': None, 'photon_persistent_disk': None, 'portworx_volume': None, 'projected': None, 'quobyte': None, 'rbd': None, 'scale_io': None, 'secret': None, 'storageos': None, 'vsphere_volume': None } ] }, 'status': { 'conditions': [ { 'last_probe_time': None, 'last_transition_time': datetime.datetime(2022, 1, 20, 15, 19, 57, tzinfo=tzutc()), 'message': None, 'reason': None, 'status': 'True', 'type': 'Initialized' }, { 'last_probe_time': None, 'last_transition_time': datetime.datetime(2022, 2, 22, 18, 32, 51, tzinfo=tzutc()), 'message': None, 'reason': None, 'status': 'True', 'type': 'Ready' }, { 'last_probe_time': None, 'last_transition_time': datetime.datetime(2022, 2, 22, 18, 32, 51, tzinfo=tzutc()), 'message': None, 'reason': None, 'status': 'True', 'type': 'ContainersReady' }, { 'last_probe_time': None, 'last_transition_time': datetime.datetime(2022, 1, 20, 15, 19, 57, tzinfo=tzutc()), 'message': None, 'reason': None, 'status': 'True', 'type': 'PodScheduled' } ], 'container_statuses': [ { 'container_id': 'docker://b5a580f66749f3c0c4a9060544b2e2a4feb77b71e805d246d1808810fe1300c2', 'image': 'registry.aliyuncs.com/google_containers/kube-apiserver:v1.23.2', 'image_id': 'docker-pullable://registry.aliyuncs.com/google_containers/kube-apiserver@sha256:63ede81b7e1fbb51669f4ee461481815f50eeed1f95e48558e3b8c3dace58a0f', 'last_state': { 'running': None, 'terminated': None, 'waiting': None }, 'name': 'kube-apiserver', 'ready': True, 'restart_count': 0, 'started': True, 'state': { 'running': { 'started_at': datetime.datetime(2022, 1, 20, 15, 19, 31, tzinfo=tzutc()) }, 'terminated': None, 'waiting': None } } ], 'ephemeral_container_statuses': None, 'host_ip': '10.0.0.4', 'init_container_statuses': None, 'message': None, 'nominated_node_name': None, 'phase': 'Running', 'pod_i_ps': [ { 'ip': '10.0.0.4' } ], 'pod_ip': '10.0.0.4', 'qos_class': 'Burstable', 'reason': None, 'start_time': datetime.datetime(2022, 1, 20, 15, 19, 57, tzinfo=tzutc()) } }
4.2、查看service
# 查看service def read_service(name, namespace="default"): # 获取服务端口号 api_response = Api_Instance.read_namespaced_service(name, namespace) return api_response
4.3、查看job
# 查看job def read_job(name, namespace="default"): api_response = Api_Batch.read_namespaced_job(name, namespace) return api_response
4.4、查看其它
都是调用这两个api对象,改下方法就行
5、修改资源
# 修改pod def replace_pod(file, name, namespace="default"): # replace: 替换容器 # patch: 可以在容器运行时直接修改属性,不删除容器 with open(file) as f: dep = yaml.safe_load(f) api_response = Api_Instance.replace_namespaced_pod(name, namespace, body=dep) return api_response # replace_pod("checkHealth.yaml" ,'mcw-healthcheck',namespace="default") old_resp = Api_Instance.read_namespaced_pod(namespace="default",name='mcw-healthcheck') old_resp.spec.containers[0].image = "centos" #只修改镜像 new_resp = Api_Instance.patch_namespaced_pod(namespace="default",name='mcw-healthcheck',body=old_resp)
如果直接创建,资源存在时执行失败。
修改报错:
edit查看,其实下面这个替换是生效的,只是这个容器已经完成了,就没有运行了
删掉容器修改时间很长才完成,重新执行创建程序
执行修改操作前,busybox
old_resp = Api_Instance.read_namespaced_pod(namespace="default",name='mcw-healthcheck') old_resp.spec.containers[0].image = "centos" #只修改镜像 new_resp = Api_Instance.patch_namespaced_pod(namespace="default",name='mcw-healthcheck',body=old_resp)
执行修改操作后。发现已经修改了镜像了。修改的原理就是:读取pod的信息,然后将这个响应信息的字段值重新定义,然后使用patch方法,修改服务端资源信息,将响应信息作为方法的body。
别的资源的修改同理,相当于执行了kubectl edit 该资源
6、读取pod日志
def read_pod_log(name, namespace="default"):
api_response = Api_Instance.read_namespaced_pod_log(name, namespace)
return api_response
res=read_pod_log("coredns-6d8c4cb4d-vctxx","kube-system")
print("res:",res)
读取pod日志,还可以读取其它的日志,把pod改成其它的就行了
7、进入pod,远程在容器中执行命令并获取返回信息
# 查看ssh、jupyter等服务的端口 #使用read_service函数 # 获取jupyter的token def exec_pod(name, command, namespace="default"): # command = ["/bin/sh","-c","jupyter notebook list"] container_stream = stream(Api_Instance.connect_get_namespaced_pod_exec, name=name, namespace=namespace, command=command, stderr=True, stdin=True, stdout=True, tty=True, _preload_content=True) return container_stream res1=exec_pod("mcw-healthcheck",command = ["/bin/sh","-c","ls /|egrep 'mcw|root' "]) print("res1: ",res1)
首先看下我们的容器,什么情况的
有点厉害,还支持这样操作
由此可知,这里命令的执行,支持反引号,支持$(),支持重定向,支持管道符
k8s sdk导出deployment配置
要使用Kubernetes SDK(例如使用Python客户端)导出Deployment配置,您可以按照以下步骤操作:
-
安装Kubernetes Python客户端库:
-
使用SDK获取Deployment信息并导出。以下是一个简单的Python脚本示例,它连接到Kubernetes集群,获取特定的Deployment,并将其配置导出为YAML格式:
在运行此脚本之前,请确保您的kubeconfig文件位于默认位置或在环境变量KUBECONFIG
指定的路径中,以便load_kube_config()
能够正确加载它。
此脚本将连接到Kubernetes集群,读取指定的Deployment配置,并以YAML格式打印出来。您可以进一步将输出写入文件以保存为配置文件。
参考链接:https://blog.csdn.net/sinat_33431419/article/details/105223726
https://www.jianshu.com/p/84ca2edc80e8