Python

Kubernetes Python SDK 官方 Client

·17 分钟阅读·6600 字

Kubernetes Python Client 的连接配置、API 对象、资源查询与自动化运维用法

📋 目录

Kubernetes Python SDK 官方 Client

Kubernetes Python SDK(官方 Python Client)详细介绍

Kubernetes Python SDK 是指官方维护的 Kubernetes Python Client,包名是 kubernetes,它允许你通过 Python 程序直接调用 Kubernetes API,实现集群资源管理、自动化运维、Operator 开发等功能。它本质上是 Kubernetes API Server 的 Python 客户端封装。(GitHub)

安装:

pip install kubernetes

官方项目:

Kubernetes Python Client (GitHub)


1. Kubernetes Python SDK 能做什么?

简单理解:

kubectl 能做的事情,大部分 Python SDK 都能做。

例如:

kubectl 命令Python SDK 能力
kubectl get pods查询 Pod
kubectl create deployment创建 Deployment
kubectl delete svc删除 Service
kubectl logs获取日志
kubectl exec进入容器
kubectl apply -f yaml创建资源
kubectl watch监听资源变化

典型应用:

1)自动化运维

例如:

每天凌晨:

  • 检查 Pod 状态

  • 自动删除异常 Job

  • 自动扩容

  • 自动重启服务

2)开发 Kubernetes Operator

例如:

自己开发:

MySQL Operator
Redis Operator
AI Training Operator

Python 可以监听 CRD:

用户创建 MySQL CR

↓

Python Controller 收到事件

↓

创建 StatefulSet

↓

创建 Service

↓

初始化数据库

类似:

kubectl
   |
API Server
   |
Python SDK
   |
Controller

2. SDK 架构

整体结构:

                 Python程序
                     |
                     |
              Kubernetes SDK
                     |
        -------------------------
        |           |           |
     Core API    Apps API    Custom API
        |           |           |
        -------------------------
                     |
              Kubernetes API Server
                     |
              etcd

SDK 本质:

Python对象
    |
HTTP REST请求
    |
Kubernetes API

例如:

Python:

v1.list_pod_for_all_namespaces()

实际:

GET /api/v1/pods

3. SDK 核心模块

安装后:

import kubernetes

主要模块:

kubernetes
│
├── client
│
├── config
│
├── watch
│
├── stream
│
└── dynamic

4. config:连接 Kubernetes

方式1:使用 kubeconfig

类似:

kubectl

读取:

~/.kube/config

代码:

from kubernetes import client, config

config.load_kube_config()

v1 = client.CoreV1Api()

对应:

kubectl config view

方式2:集群内部运行

例如:

Python程序运行在 Pod:

Pod
 |
ServiceAccount
 |
API Server

使用:

config.load_incluster_config()

例如:

Operator:

namespace:
 kube-system

pod:
 mysql-controller

里面:

config.load_incluster_config()

自动读取:

/var/run/secrets/kubernetes.io/serviceaccount/

5. client:API对象

client 是核心。

例如:

client.CoreV1Api()
client.AppsV1Api()
client.BatchV1Api()

对应 Kubernetes API Group。


Core API

管理:

  • Pod

  • Service

  • ConfigMap

  • Secret

  • Namespace

例如:

from kubernetes import client,config

config.load_kube_config()

api = client.CoreV1Api()

pods = api.list_pod_for_all_namespaces()

for pod in pods.items:
    print(
        pod.metadata.namespace,
        pod.metadata.name
    )

输出:

default nginx-xxx
kube-system coredns-xxx

6. 查询 Deployment

Deployment 属于:

apps/v1

所以:

apps = client.AppsV1Api()

查询:

deployments = apps.list_deployment_for_all_namespaces()

for d in deployments.items:
    print(
        d.metadata.name,
        d.status.ready_replicas
    )

类似:

kubectl get deploy -A

7. 创建资源

创建 Namespace

from kubernetes import client

namespace = client.V1Namespace(
    metadata=client.V1ObjectMeta(
        name="test"
    )
)

api.create_namespace(namespace)

等价:

apiVersion: v1
kind: Namespace
metadata:
 name:test

8. 创建 Pod

Python:

pod = client.V1Pod(

metadata=
client.V1ObjectMeta(
    name="nginx"
),

spec=
client.V1PodSpec(

containers=[

client.V1Container(
name="nginx",
image="nginx"
)

]

)

)

api.create_namespaced_pod(
namespace="default",
body=pod
)

等价:

kubectl run nginx --image nginx

9. Deployment 创建

例子:

deployment = client.V1Deployment(

metadata=
client.V1ObjectMeta(
name="nginx"
),

spec=
client.V1DeploymentSpec(

replicas=3,

selector=
client.V1LabelSelector(
match_labels={
"app":"nginx"
}
),

template=
client.V1PodTemplateSpec(

metadata=
client.V1ObjectMeta(
labels={
"app":"nginx"
}
),

spec=
client.V1PodSpec(

containers=[

client.V1Container(
name="nginx",
image="nginx"
)

]

)

)

)

)

apps.create_namespaced_deployment(
namespace="default",
body=deployment
)

10. Watch机制(非常重要)

Kubernetes Controller 的核心:

Watch

例如:

监听 Pod:

from kubernetes import watch

w = watch.Watch()

for event in w.stream(
    api.list_pod_for_all_namespaces
):

    print(
        event["type"],
        event["object"].metadata.name
    )

输出:

ADDED nginx
MODIFIED nginx
DELETED nginx

这就是:

Controller Pattern:

Observe
   |
Compare
   |
Act

11. 获取 Pod 日志

等价:

kubectl logs nginx

Python:

logs = api.read_namespaced_pod_log(
    name="nginx",
    namespace="default"
)

print(logs)

12. exec进入容器

等价:

kubectl exec -it nginx -- bash

Python:

from kubernetes.stream import stream

resp = stream(

api.connect_get_namespaced_pod_exec,

"nginx",
"default",

command=[
"/bin/bash"
],

stderr=True,
stdin=True,
stdout=True,
tty=True

)

print(resp)

13. 操作 CRD

Kubernetes 最大特点:

扩展 API。

例如:

安装:

kind: MySQL

自己的资源:

mysql.example.com

Python:

from kubernetes import client

custom = client.CustomObjectsApi()

mysql = custom.get_namespaced_custom_object(

group="example.com",

version="v1",

namespace="default",

plural="mysqls",

name="mysql01"

)

14. Dynamic Client

官方 Client 的问题:

对象很多:

V1Pod
V1Service
V1Deployment
...

Dynamic Client 类似 kubectl:

from kubernetes import dynamic

client = dynamic.DynamicClient(api_client)

pods = client.resources.get(
    api_version="v1",
    kind="Pod"
)

优点:

  • 不需要提前知道类型

  • 更适合 Operator


15. Python SDK 和 kubectl 对比

kubectlPython SDK
人工操作★★★★★★★
脚本自动化★★★★★★★★
CI/CD★★★★★★★★
Operator★★★★★★
复杂逻辑★★★★★★★
交互式管理★★★★★★★

16. 常见生产应用

场景1:自动清理失败 Pod

逻辑:

每分钟:

查询Pod

↓

判断:

CrashLoopBackOff

↓

删除

↓

等待Deployment恢复

场景2:自动扩容

例如:

CPU:

>80%

执行:

scale deployment replicas=10

场景3:开发 Operator

Python生态:

推荐框架:

Kopf

示例:

import kopf

@kopf.on.create(
"example.com",
"v1",
"mysqls"
)

def create(spec, name, **kwargs):

    print(
        "create mysql",
        name
    )

17. SDK源码结构

大概:

kubernetes/

├── client/

│   ├── api/
│   │
│   ├── models/
│   │
│   └── api_client.py

├── config/

├── watch/

└── stream/

其中:

api_client.py

负责:

HTTP请求:

GET
POST
DELETE
PATCH

models

对应 Kubernetes 对象:

例如:

V1Pod
V1Container
V1Service

18. 性能注意

生产环境:

不要:

while True:

    list_pods()

因为:

API Server压力大

应该:

使用:

Watch
Informer
Controller模式

19. 学习路线(运维方向)

如果目标是 K8s运维自动化,建议:

第一阶段

掌握:

client
config
CoreV1Api
AppsV1Api

实现:

  • 查询资源

  • 创建资源

  • 删除资源


第二阶段

学习:

watch
CustomObjectsApi
CRD

开始写:

Operator


第三阶段

结合:

Prometheus
+
Python SDK
+
Webhook
+
Controller

做:

自动化平台。


20. 面试常问问题

Q1:

Python SDK 和 kubectl 什么关系?

答:

kubectl 是 Kubernetes API 的命令行客户端,Python SDK 是 Kubernetes API 的程序化客户端,本质都是调用 API Server。


Q2:

如何监听 Pod 状态?

答:

使用 watch.Watch,通过 list/watch API 持续监听资源变化。


Q3:

Operator 为什么需要 Python SDK?

答:

Operator 本质是一个 Controller,需要通过 API Server 创建、更新、删除 Kubernetes 资源,SDK提供API访问能力。


Q4:

Python SDK 如何访问集群?

答:

两种:

  1. kubeconfig

  2. in-cluster ServiceAccount


总结

如果你是 Kubernetes 运维工程师,Python SDK 最值得掌握的部分:

⭐⭐⭐⭐⭐
config

⭐⭐⭐⭐⭐
CoreV1Api

⭐⭐⭐⭐⭐
AppsV1Api

⭐⭐⭐⭐⭐
watch

⭐⭐⭐⭐
CustomObjectsApi

⭐⭐⭐⭐
stream

⭐⭐⭐⭐⭐
Operator开发

它是从:

“会用 Kubernetes”

进阶到:

“能开发 Kubernetes 自动化系统”

的重要工具。(GitHub)

Yanche Blog

记录云原生、Linux、数据库等技术领域的学习心得,以及日常生活的思考与感悟。

© 2026 Yanche Blog. All rights reserved.

Powered by Astro