kubernetes-10-python 操作 kubernetes

1 kubeconfig file authentication

CMD>conda activate python36
CMD>pip install kubernetes

First introduce the SDK support library. Then copy the content of the config file of ~/.kube to the local directory, save it as the file kubeconfig.yaml, and then run the following python code.
#cp /root/.kube/config /root/kubeconfig.yaml
Put the code in the project directory.

2 API usage

2.1 List resource information

2.1.1 List namespaces

#encoding:utf8
from kubernetes import client, config
config.kube_config.load_kube_config(config_file = "kubeconfig.yaml")
#获取API的CoreV1Api版本对象
v1 = client.CoreV1Api()

#列出 namespaces
for ns in v1.list_namespace().items:
    print(ns.metadata.name)

admin
auth
cert-manager
default
istio-system
knative-serving
kube-node-lease
kube-public
kube-system
kubeflow
local-path-storage

2.1.2 List services

#encoding:utf8
from kubernetes import client, config
config.kube_config.load_kube_config(config_file = "kubeconfig.yaml")
#获取API的CoreV1Api版本对象
v1 = client.CoreV1Api()

# 列出所有的services
res = v1.list_service_for_all_namespaces(watch=False)
i = 0
for re in res.items:
    print(i,re.kind, re.metadata.namespace, re.metadata.name, re.spec.cluster_ip, re.spec.ports)
    i = i+1

0 None admin me 10.110.40.152 [{‘name’: ‘http-me’,
‘node_port’: None,
‘port’: 80,
‘protocol’: ‘TCP’,
‘target_port’: 8888}]
1 None auth dex 10.101.7.135 [{‘name’: ‘dex’,
‘node_port’: 32000,
‘port’: 5556,
‘protocol’: ‘TCP’,
‘target_port’: 5556}]

2.1.3 List pods

#encoding:utf8
from kubernetes import client, config
config.kube_config.load_kube_config(config_file = "kubeconfig.yaml")
#获取API的CoreV1Api版本对象
v1 = client.CoreV1Api()


# 列出所有的pod
res = v1.list_pod_for_all_namespaces(watch=False)
i = 0
for re in res.items:
    print(i, re.status.pod_ip, re.metadata.namespace, re.metadata.name)
    i = i+1

0 10.244.1.33 admin me-0
1 10.244.1.248 auth dex-d468d6b64-lbphz
2 10.244.1.27 cert-manager cert-manager-5d849b9888-wt5zk

Guess you like

Origin blog.csdn.net/qq_20466211/article/details/113803442