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

如何使用kr8s Python库导出Kubernetes集群现有资源为YAML清单?

使用kr8s Python库导出Kubernetes资源为YAML清单

当然可以用kr8s实现Kubernetes现有资源到YAML清单的反向导出,下面是具体的操作步骤和代码示例:

1. 安装kr8s库

首先确保你已经安装了kr8s:

pip install kr8s

2. 导出单个资源

如果你只需要导出某个特定资源(比如一个Deployment),可以用以下代码:

import kr8s

# 连接集群,默认读取kubeconfig配置,和kubectl行为一致
api = kr8s.api()

# 获取指定命名空间下的目标Deployment
deploy = api.get("deployments", name="my-deployment", namespace="default")

# 导出为可直接apply的YAML,prune=True会自动移除自动生成的字段(如status、uid等)
print(deploy.to_yaml(prune=True))

3. 导出某类所有资源

如果要导出某一类型的所有资源(比如默认命名空间下的所有ConfigMap),可以批量导出到文件:

import kr8s
from pathlib import Path

api = kr8s.api()
# 获取默认命名空间下的所有ConfigMap
configmaps = api.list("configmaps", namespace="default")

# 逐个写入到单独的YAML文件
for cm in configmaps:
    file_path = Path(f"{cm.metadata.name}.yaml")
    with file_path.open("w") as f:
        f.write(cm.to_yaml(prune=True))

4. 导出整个命名空间的多类资源

如果需要导出整个命名空间下的多种资源(比如Deployment、Service、ConfigMap等),可以按资源类型分类保存:

import kr8s
from pathlib import Path

api = kr8s.api()
target_namespace = "default"
# 定义需要导出的资源类型列表,可根据需求添加或删除
resource_types = ["deployments", "services", "configmaps", "secrets"]

for rt in resource_types:
    resources = api.list(rt, namespace=target_namespace)
    # 创建按命名空间和资源类型分类的目录
    save_dir = Path(target_namespace) / rt
    save_dir.mkdir(parents=True, exist_ok=True)
    
    for res in resources:
        file_path = save_dir / f"{res.metadata.name}.yaml"
        with file_path.open("w") as f:
            f.write(res.to_yaml(prune=True))

关键说明

  • to_yaml(prune=True) 是核心参数:它会自动过滤掉Kubernetes创建资源时生成的非必要字段(如status、metadata.uid、metadata.creationTimestamp等),保证导出的YAML可以直接用kubectl apply -f命令重新应用。
  • 集群连接:kr8s默认和kubectl使用相同的配置逻辑,会自动读取~/.kube/config,也可以通过环境变量或kr8s.api()的参数指定自定义集群配置。
  • 跨命名空间导出:如果需要导出所有命名空间的资源,只需去掉代码中的namespace参数即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 14:14:57