Python之K8S API接口大全


一、常用资源接口类实例化

core_api = client.CoreV1Api()  		# namespace,pod,service,pv,pvc
apps_api = client.AppsV1Api()  		# deployment
networking_api = client.NetworkingV1beta1Api()  # ingress
storage_api = client.StorageV1Api()  			# storage_class

二、操作Deployment

2.1.创建

namespace = "default"
name = "api-test"
replicas = 3
labels = {'a':'1', 'b':'2'}  # 不区分数据类型,都要加引号
image = "nginx"
body = client.V1Deployment(
            api_version="apps/v1",
            kind="Deployment",
            metadata=client.V1ObjectMeta(name=name),
            spec=client.V1DeploymentSpec(
                replicas=replicas,
                selector={'matchLabels': labels},
                template=client.V1PodTemplateSpec(
                    metadata=client.V1ObjectMeta(labels=labels),
                    spec=client.V1PodSpec(
                        containers=[client.V1Container(
                            name="web",
                            image=image
                        )]
                    )
                ),
            )
        )
try:
    apps_api.create_namespaced_deployment(namespace=namespace, body=body)
except Exception as e:
    status = getattr(e, "status")
    if status == 400:
        print(e)
        print("格式错误")
    elif status == 403:
        print("没权限")

2.2.查询

for dp in apps_api.list_deployment_for_all_namespaces().items:
    print(dp.metadata.name)

2.3.删除

namespace = "default"
name = "api-test"
apps_api.delete_namespaced_deployment(namespace=namespace, name=name)

三、操作Service

3.1.创建

namespace = "default"
name = "api-test"
selector = {'a':'1', 'b':'2'}  # 不区分数据类型,都要加引号
port = 80
target_port = 80
type = "NodePort"
body = client.V1Service(
    api_version="v1",
    kind="Service",
    metadata=client.V1ObjectMeta(
        name=name
    ),
    spec=client.V1ServiceSpec(
        selector=selector,
        ports=[client.V1ServicePort(
            port=port,
            target_port=target_port
        )],
        type=type
    )
)
core_api.create_namespaced_service(namespace=namespace, body=body)

3.2.查询

for svc in core_api.list_namespaced_service(namespace="default").items:
    print(svc.metadata.name)

3.3.删除

core_api.delete_namespaced_service(namespace=namespace, name=name)
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页