如何用Python操作Kubernetes集群?

进阶PythonDocker

答题要点

from kubernetes import client, config, watch

# 加载配置
config.load_kube_config()  # 本地kubeconfig
# config.load_incluster_config()  # 集群内Pod中使用

# API客户端
v1 = client.CoreV1Api()
apps_v1 = client.AppsV1Api()
batch_v1 = client.BatchV1Api()

# 列出Pod
pods = v1.list_namespaced_pod(namespace='default')
for pod in pods.items:
    print(f"{pod.metadata.name}: {pod.status.phase}")

# 创建Pod
pod_manifest = {
    'apiVersion': 'v1',
    'kind': 'Pod',
    'metadata': {'name': 'etl-job'},
    'spec': {
        'containers': [{
            'name': 'etl',
            'image': 'my-etl:latest',
            'command': ['python', 'run_etl.py']
        }],
        'restartPolicy': 'Never'
    }
}
v1.create_namespaced_pod(namespace='default', body=pod_manifest)

# 创建Job
job_manifest = client.V1Job(
    metadata=client.V1ObjectMeta(name='data-processing'),
    spec=client.V1JobSpec(
        template=client.V1PodTemplateSpec(
            spec=client.V1PodSpec(
                containers=[client.V1Container(
                    name='processor',
                    image='processor:latest'
                )],
                restart_policy='Never'
            )
        )
    )
)
batch_v1.create_namespaced_job(namespace='default', body=job_manifest)

# Watch事件
w = watch.Watch()
for event in w.stream(v1.list_namespaced_pod, namespace='default', timeout_seconds=60):
    print(f"{event['type']}: {event['object'].metadata.name}")

完整解析在题库里看

核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。

去练这道题

回知识库看这一块

同一能力的其他题