記錄一下 python和k8s互動方式,涵蓋配置/configmap/ingress/pod/deployment/serivce等;
from kubernetes import client, config # type: ignore
from sites.config import ROOT_PATH
# 命令空間
NAMESPACE = "namespace_name"
class K8sHandler(object):
def __init__(self) -> None:
kubeconfig = ROOT_PATH / "kubeconfig"
config.load_kube_config(str(kubeconfig))
# 資源介面類例項化
self.apps_api = client.AppsV1Api()
self.core_api = client.CoreV1Api()
self.networking_api = client.NetworkingV1Api()
def get_configmaps(self, namespace=NAMESPACE) -> list:
data = []
for cm in self.core_api.list_namespaced_config_map(namespace=namespace).items:
data.append(cm.metadata.name)
return data
def create_configmap(self, body, namespace=NAMESPACE) -> None:
self.core_api.create_namespaced_config_map(namespace=namespace, body=body)
def delete_configmap(self, name, namespace=NAMESPACE) -> None:
self.core_api.delete_namespaced_config_map(
name=name, namespace=namespace, body=client.V1DeleteOptions()
)
def get_pods(self, namespace=NAMESPACE) -> list:
data = []
for dp in self.core_api.list_namespaced_pod(namespace=namespace).items:
data.append(dp.metadata.name)
return data
def delete_pod(self, name, namespace=NAMESPACE) -> None:
self.core_api.delete_namespaced_pod(
name=name, namespace=namespace, body=client.V1DeleteOptions()
)
def get_deployments(self, namespace=NAMESPACE) -> list:
data = []
for dp in self.apps_api.list_namespaced_deployment(namespace=namespace).items:
data.append(dp.metadata.name)
return data
def create_deployment(self, body, namespace=NAMESPACE) -> None:
self.apps_api.create_namespaced_deployment(namespace=namespace, body=body)
def delete_deployment(self, name, namespace=NAMESPACE) -> None:
self.apps_api.delete_namespaced_deployment(
name=name, namespace=namespace, body=client.V1DeleteOptions()
)
def get_services(self, namespace=NAMESPACE) -> list:
data = []
for cm in self.core_api.list_namespaced_service(namespace=namespace).items:
data.append(cm.metadata.name)
return data
def create_service(self, body, namespace=NAMESPACE) -> None:
self.core_api.create_namespaced_service(namespace=namespace, body=body)
def delete_service(self, name, namespace=NAMESPACE) -> None:
self.core_api.delete_namespaced_service(
name=name, namespace=namespace, body=client.V1DeleteOptions()
)
def get_ingress(self, namespace=NAMESPACE) -> list:
data = []
for cm in self.networking_api.list_namespaced_ingress(namespace=namespace).items:
data.append(cm.metadata.name)
return data
def create_ingress(self, body, namespace=NAMESPACE) -> None:
self.networking_api.create_namespaced_ingress(namespace=namespace, body=body)
def delete_ingress(self, name, namespace=NAMESPACE) -> None:
self.networking_api.delete_namespaced_ingress(
name=name, namespace=namespace, body=client.V1DeleteOptions()
)