You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Kubernetes Python API修复处于Terminating状态的命名空间

解决Kubernetes命名空间卡在Terminating状态的Python脚本问题

问题原因

你手动执行的kubectl replace --raw "/api/v1/namespaces/<namespace>/finalize"是直接调用了Kubernetes API的命名空间终态化专用端点,而Python客户端的replace_namespace方法调用的是标准命名空间替换端点(/api/v1/namespaces/{name})。当命名空间处于Terminating状态时,标准端点不会处理终态器的修改操作,必须通过专用的/finalize端点才能完成终态器的清空。

修复后的Python脚本

提供两种可行实现方式:

方式1:模拟kubectl的--raw调用(推荐)

完全对齐手动命令的逻辑,直接调用K8s API的/finalize端点:

from kubernetes import config, client
import json

config.load_kube_config()
core_v1 = client.CoreV1Api()

# 筛选所有处于Terminating状态的命名空间
terminating_ns = [
    ns.metadata.name for ns in core_v1.list_namespace().items
    if ns.status.phase == "Terminating"
]

print(f"检测到 {len(terminating_ns)} 个处于Terminating状态的命名空间")

for ns_name in terminating_ns:
    # 获取目标命名空间的完整对象
    ns = core_v1.read_namespace(ns_name)
    # 清空终态器列表
    ns.spec.finalizers = []
    
    # 序列化对象并调用/finalize端点
    request_body = json.loads(client.ApiClient().sanitize_for_serialization(ns))
    try:
        response = core_v1.api_client.call_api(
            f"/api/v1/namespaces/{ns_name}/finalize",
            "PUT",
            body=request_body,
            response_type="Namespace",
            auth_settings=['BearerToken']
        )
        print(f"成功清理命名空间 {ns_name} 的终态器")
    except Exception as e:
        print(f"清理命名空间 {ns_name} 失败: {str(e)}")

方式2:使用Strategic Merge Patch操作

通过补丁操作直接修改终态器字段:

from kubernetes import config, client

config.load_kube_config()
core_v1 = client.CoreV1Api()

terminating_ns = [
    ns.metadata.name for ns in core_v1.list_namespace().items
    if ns.status.phase == "Terminating"
]

for ns_name in terminating_ns:
    try:
        # 构造补丁内容,清空spec.finalizers
        patch_body = {"spec": {"finalizers": []}}
        core_v1.patch_namespace(ns_name, patch_body)
        print(f"成功清理命名空间 {ns_name} 的终态器")
    except Exception as e:
        print(f"清理命名空间 {ns_name} 失败: {str(e)}")

验证方法

执行脚本后,可通过以下命令确认修复效果:
kubectl get ns
若原本卡住的命名空间已消失,则说明修复成功。

内容的提问来源于stack exchange,提问作者user3002166

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 23:43:14