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}}
单个pod
数据量有点大
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())
}
}
pod打印信息
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)
首先看下我们的容器,什么情况的
有点厉害,还支持这样操作
由此可知,这里命令的执行,支持反引号,支持$(),支持重定向,支持管道符
参考链接:https://blog.csdn.net/sinat_33431419/article/details/105223726
https://www.jianshu.com/p/84ca2edc80e8
kubernetes之python调用的更多相关文章
- Python调用Prometheus监控数据并计算
Prometheus是什么 Prometheus是一套开源监控系统和告警为一体,由go语言(golang)开发,是监控+报警+时间序列数 据库的组合.适合监控docker容器.因为kubernetes ...
- 【初学python】使用python调用monkey测试
目前公司主要开发安卓平台的APP,平时测试经常需要使用monkey测试,所以尝试了下用python调用monkey,代码如下: import os apk = {'j': 'com.***.test1 ...
- python调用py中rar的路径问题。
1.python调用py,在py中的os.getcwd()获取的不是py的路径,可以通过os.path.split(os.path.realpath(__file__))[0]来获取py的路径. 2. ...
- python调用其他程序或脚本方法(转)
python运行(调用)其他程序或脚本 在Python中可以方便地使用os模块运行其他的脚本或者程序,这样就可以在脚本中直接使用其他脚本,或者程序提供的功能,而不必再次编写实现该功能的代码.为了更好地 ...
- python调用c\c++
前言 python 这门语言,凭借着其极高的易学易用易读性和丰富的扩展带来的学习友好性和项目友好性,近年来迅速成为了越来越多的人们的首选.然而一旦拿python与传统的编程语言(C/C++)如来比较的 ...
- Python调用C++
/***gcc -o libpycall.so -shared -fPIC pycall.c*/ #include <stdio.h> #include <stdlib.h> ...
- 使用Python调用Flickr API抓取图片数据
Flickr是雅虎旗下的图片分享网站,上面有全世界网友分享的大量精彩图片,被认为是专业的图片网站.其API也很友好,可以实现多种功能.这里我使用了Python调用其API获得了大量的照片数据.需要注意 ...
- python调用zabbix接口实现Action配置
要写这篇博客其实我的内心是纠结的,老实说,我对zabbix的了解实在不多.但新公司的需求不容置疑,当我顶着有两个头大的脑袋懵懵转入运维领域时,面前摆着两百多组.上千台机器等着写入zabbix监控的需求 ...
- linux下python调用c模块
在C调用Python模块时需要初始化Python解释器,导入模块等,但Python调用C模块却比较简单,下面还是以helloWorld.c 和 main.py 做一说明: (1)编写C代码,hel ...
- python 调用nmap
1.系统中需要安装nmap 2.系统中安装pip 2.安装python调用nmap的lib包 命令为:pip install python-nmap 以下是在centos系统下安装成功后的截图 在命令 ...
随机推荐
- Redis 19 SpringBoot集成
概述 SpringBoot 整合 Redis 是使用 SpringData 实现的. SpringData 是与 SpringBoot 齐名的顶级项目,整合了对常用数据库的模板型操作. 在 Sprin ...
- 基于 Scriptable 从零开始美化iOS桌面(一)
今天我为大家带来新的作品,iOS17桌面组件神器(Scriptable)原创脚本,精美作品分享!喜欢的话就点关注吧!更多脚本正在路上... * script : ONE-Progress.js * v ...
- 重新整理asp.net core 实操篇——简介
前言 实操篇和底层刨析分开的,<重新整理.net core 计1400篇>是探索底层概念. 介绍asp.net core之前先介绍.net core. .NET Core 是一个通用的开放 ...
- 第四章:if else switch使用
/* * @Issue: 输入整数a和b,若a²+b²大于100,则输出a²+b²之和的百位以上的数字,否则直接输出a²+b²的和 * @Author: 一届书生 * @LastEditTime : ...
- python抽帧及生成高质量的GIF图
python抽帧及生成高质量的GIF图 对视频进行抽帧只需要两个模块即可: opencv-python (cv2) opencv-contrib-python 我们都知道视频有分辨率,即视频的宽度与高 ...
- 埃森哲携手阿里云,采用K8s容器云服务为客户提供无限弹性
简介: 埃森哲作为全球领先的专业服务公司,在数字化.云计算等领域拥有全球领先的能力,我们在多年的实际客户项目中,找到并沉淀出了适合企业数字化转型的方法论,积累了丰富的落地经验. 作者:姚迪.周警伟 随 ...
- 技术实践第三期|HashTag在Redis集群环境下的使用
简介:欢迎了解友盟+技术干货第三期内容:Redis集群环境如何按照前缀批量删除缓存.希望能对开发者们在实际应用中有所帮助. 一.背景 数据源列表添加缓存支持,types字段可传多值,如app, mi ...
- 如何保证 Serverless 业务部署更新的一致性?
简介: 代码在其他场景被更新,需要我们在当前得到感知,这个事情其实是非常重要的,和代码的安全发布密不可少.而此时,通过 Serverless Devs 是可以做到的. 作者|Anycodes 从我做 ...
- [FAQ] Quasar SSR: Hydration completed but contains mismatches.
使用 Quasar SSR 模式在 build 编译目标代码时,如果模板里有在服务端渲染阶段可能无法识别的变量,一般会出现这类提示. 比如在 layout 模板里使用了 this.$q.this.$r ...
- Unity3D OpenVR 虚拟现实 保龄球打砖块游戏开发
据说水哥买了 Valve Index 设备,既然这个设备这么贵,不开发点有(zhi)趣(zhang)游戏就感觉对不起这个设备.本文将来开始着手开发一个可玩性不大,观赏性极强的保龄球打砖块游戏.这仅仅只 ...