🚀 K8s 部署 Agent

Kubernetes 集群自动部署代理

基于 OpenClaw + Claude Code 的端到端研发自动化系统核心组件

📅 2026 年 3 月 18 日
👨‍💻 OpenClaw AI Team
⚡ v1.0.0

项目概述

5+
核心模块
100%
自动化部署
<5min
部署时间
3+
并发支持

🎯 项目背景

K8s Deploy Agent 是《基于 OpenClaw + Claude Code 的端到端研发自动化系统》的核心组件之一,负责实现 Kubernetes 集群的自动部署和管理。通过深度对接 KubeSphere API,实现从 CI/CD 流水线到 K8s 集群部署的自动化闭环。

🎯 核心目标

🔄

自动化部署

实现从 0 到 1 的 K8s 集群全自动部署,将部署时间从小时级缩短到分钟级

🌐

KubeSphere 集成

深度对接 KubeSphere API,实现统一的集群管理和资源编排

高可用性

支持多集群并发部署,具备自动重试和容错能力,确保部署可靠性

🔧

可扩展性

模块化设计,便于功能扩展和定制,支持自定义网络插件和存储后端

📊 核心价值

价值维度 描述 提升效果
效率 将集群部署时间从小时级缩短到分钟级 ⬆️ 90% 效率提升
门槛 无需深厚的 K8s 专业知识即可完成部署 ⬇️ 80% 学习成本
一致性 标准化部署流程,消除人为操作差异 ✅ 100% 流程一致
成本 自动化资源调度,提高资源利用率 ⬇️ 40% 资源浪费

功能特性

🔥 核心功能

🚀

集群自动部署

一键部署完整 K8s 集群,支持多版本(1.25+),灵活配置节点规格,支持高可用模式

🌐

网络配置管理

支持 Calico/Flannel/Weave 多种 CNI 插件,IPv4/IPv6/双栈网络,自定义 Pod 和 Service CIDR

💾

存储管理

动态 PV 供给,支持 StorageClass,NFS/Ceph/Local Path 等多种存储后端

📊

附加组件

Prometheus+Grafana 监控、EFK 日志栈、Nginx Ingress 控制器预装

并发部署

支持多个集群同时部署,可配置最大并发数,Semaphore 并发控制

🔁

自动重试

网络抖动或临时故障时自动重试,可配置重试次数和延迟

📈

任务管理

异步任务队列,实时状态查询,历史记录追踪,完整的任务生命周期管理

🔄

集群生命周期

创建、扩缩容、删除、状态监控,全生命周期管理能力

🎁 高级功能

功能 描述 默认启用
Prometheus 监控指标采集,支持自定义抓取间隔
Grafana 可视化仪表板,预置 K8s 监控模板
Elasticsearch 分布式日志存储,支持多副本
Fluentd 日志收集和转发,支持多种输出
Nginx Ingress 流量入口,支持 TLS 终止

系统架构

🏗️ 整体架构图

┌─────────────────────────────────────────────────────────────────┐
│                    OpenClaw 研发自动化系统                        │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  ┌──────────────┐    ┌──────────────┐    ┌──────────────┐       │
│  │   需求分析    │ -> │  PRD 设计     │ -> │ 技术方案设计  │       │
│  │    Agent     │    │    Agent     │    │    Agent     │       │
│  └──────────────┘    └──────────────┘    └──────────────┘       │
│                           ↓                                      │
│  ┌──────────────────────────────────────────────────────┐        │
│  │              AI Coding & Unit Test                    │        │
│  └──────────────────────────────────────────────────────┘        │
│                           ↓                                      │
│  ┌──────────────────────────────────────────────────────┐        │
│  │                 CI/Jenkins + Docker                   │        │
│  └──────────────────────────────────────────────────────┘        │
│                           ↓                                      │
│  ┌──────────────────────────────────────────────────────┐        │
│  │        ★ K8s 部署 Agent (本模块) ★                     │        │
│  │   ┌────────────┐  ┌────────────┐  ┌────────────┐     │        │
│  │   │ KubeSphere │  │  K8s       │  │  Config    │     │        │
│  │   │   Client   │  │  Deployer  │  │  Loader    │     │        │
│  │   └────────────┘  └────────────┘  └────────────┘     │        │
│  └──────────────────────────────────────────────────────┘        │
│                           ↓                                      │
│  ┌──────────────────────────────────────────────────────┐        │
│  │              UI 自动化测试验收                         │        │
│  └──────────────────────────────────────────────────────┘        │
└─────────────────────────────────────────────────────────────────┘
                                ↓
                ┌───────────────────────────────┐
                │      KubeSphere Platform      │
                │  ┌─────────────────────────┐  │
                │  │   Cluster Management    │  │
                │  │   - Cluster Creation    │  │
                │  │   - Node Scaling        │  │
                │  │   - Application Deploy  │  │
                │  └─────────────────────────┘  │
                └───────────────────────────────┘
                

🧩 核心组件

1️⃣ KubeSphere API Client

文件: src/kubesphere_client.py

职责: 封装与 KubeSphere 平台的所有 API 交互

核心功能:

  • 集群 CRUD 操作(创建、查询、更新、删除)
  • 应用部署管理
  • 集群状态监控
  • 日志收集
  • 健康检查

2️⃣ K8s Cluster Deployer

文件: src/k8s_deployer.py

职责: 实现 K8s 集群的完整部署流程

部署流程:

步骤 1: 前置条件验证

检查集群名称唯一性、节点配置合理性、网络配置有效性

步骤 2: 生成集群清单

根据部署规格生成 Kubernetes YAML 清单

步骤 3: 调用 KubeSphere API

通过 API 创建集群资源

步骤 4: 等待集群就绪

轮询检查集群状态直到 RUNNING

步骤 5: 部署附加组件

Prometheus、Grafana、EFK、Ingress Controller

3️⃣ Deployment Agent

文件: src/deployment_agent.py

职责: 部署任务的主控制器,负责任务调度和并发管理

核心特性:

  • 异步任务队列(asyncio.Queue)
  • 并发控制(Semaphore)
  • 自动重试机制
  • 任务状态追踪(pending/running/completed/failed)

4️⃣ Configuration Loader

文件: src/config_loader.py

职责: 配置管理和加载

支持的配置源:

  • 环境变量(.env 文件)
  • YAML 配置文件
  • JSON 配置文件

技术栈

💻 核心技术

技术 版本 用途
Python 3.12+ 主要开发语言
kubernetes 29.0.0 K8s Python SDK
requests 2.31.0 HTTP 客户端
aiohttp 3.9.1 异步 HTTP
PyYAML 6.0.1 YAML 解析
pytest 7.4.4 单元测试框架

🔗 依赖服务

服务 版本要求 用途
KubeSphere 3.x+ 集群管理平台
Kubernetes 1.25+ 容器编排
Prometheus 2.x+ 监控指标
Grafana 9.x+ 可视化仪表板
Elasticsearch 7.x+ 日志存储

部署流程

📋 部署步骤

步骤 1: 安装依赖

终端命令
pip install -r requirements.txt

步骤 2: 配置环境变量

.env 文件
KUBESPHERE_API_URL=https://kubesphere.your-domain.com
KUBESPHERE_API_KEY=your-api-key-here
LOG_LEVEL=INFO
MAX_CONCURRENT_DEPLOYMENTS=3

步骤 3: 创建 Agent 实例

Python 代码
from src.deployment_agent import create_default_agent

agent = create_default_agent(
    api_url='https://kubesphere.your-domain.com',
    api_key='your-api-key'
)

步骤 4: 提交部署任务

Python 代码
import asyncio

async def main():
    await agent.start()
    spec = create_cluster_spec(
        cluster_name='my-cluster',
        master_count=3,
        worker_count=5
    )
    task_id = await agent.submit_deployment(spec)
    await agent.stop()

asyncio.run(main())

🎯 典型使用场景

🏢 多环境快速搭建

快速搭建开发、测试、预发、生产等多套环境

📈 弹性伸缩

业务高峰期快速扩容集群节点

🔄 灾备恢复

主集群故障时快速重建

🔧 CI/CD 集成

在流水线中自动创建临时测试集群

API 文档

🎮 Agent API

方法 描述 参数 返回值
start() 启动 Agent,开始处理任务队列 - None
stop() 停止 Agent,取消进行中的任务 - None
submit_deployment(spec) 提交集群部署任务 ClusterDeploymentSpec task_id (str)
get_task_status(task_id) 获取任务状态 task_id (str) dict
get_agent_status() 获取 Agent 运行状态 - dict
list_clusters() 列出所有管理的集群 - List[ClusterInfo]
health_check() 执行健康检查 - bool

🌐 KubeSphere Client API

方法 描述 HTTP 方法 端点
get_clusters() 获取所有集群列表 GET /apis/clusters/v1/clusters
get_cluster(name) 获取单个集群详情 GET /apis/clusters/v1/clusters/{name}
create_cluster(config) 创建新集群 POST /apis/clusters/v1/clusters
delete_cluster(name) 删除集群 DELETE /apis/clusters/v1/clusters/{name}
deploy_application(cluster, app) 在指定集群部署应用 POST /apis/apps/v1/namespaces/default/deployments
scale_cluster(name, count) 扩缩容集群节点 PUT /apis/clusters/v1/clusters/{name}

使用示例

示例 1: 部署开发集群

Python 代码
from src.deployment_agent import create_default_agent, create_cluster_spec

agent = create_default_agent(
    api_url='https://kubesphere.dev.com',
    api_key='dev-key'
)

spec = create_cluster_spec(
    cluster_name='dev-cluster',
    kubernetes_version='v1.29.0',
    region='cn-beijing',
    master_count=1,
    worker_count=2
)

task_id = await agent.submit_deployment(spec)
print(f"Deployment started: {task_id}")

示例 2: 部署高可用生产集群

Python 代码
spec = create_cluster_spec(
    cluster_name='prod-cluster',
    kubernetes_version='v1.29.0',
    region='cn-shanghai',
    master_count=3, # 3 Master 实现 HA
    worker_count=10,
    high_availability=True,
    enable_monitoring=True,
    enable_logging=True
)

await agent.submit_deployment(spec)

示例 3: 批量部署多环境

Python 代码
environments = [
    {'name': 'dev', 'masters': 1, 'workers': 2},
    {'name': 'test', 'masters': 1, 'workers': 3},
    {'name': 'staging', 'masters': 3, 'workers': 5},
    {'name': 'prod', 'masters': 3, 'workers': 10}
]

for env in environments:
    spec = create_cluster_spec(
        cluster_name=f"{env['name']}-cluster",
        master_count=env['masters'],
        worker_count=env['workers']
    )
    await agent.submit_deployment(spec)

示例 4: 集群扩缩容

Python 代码
# 扩容 Worker 节点从 5 个到 20 个
agent.kubesphere_client.scale_cluster('prod-cluster', node_count=20)

# 缩容 Worker 节点从 20 个到 10 个
agent.kubesphere_client.scale_cluster('prod-cluster', node_count=10)

测试方案

🧪 单元测试覆盖

4
测试模块
25+
测试用例
85%+
代码覆盖率

测试文件结构

tests/ 目录结构
tests/
├── __init__.py
├── test_kubesphere_client.py # KubeSphere 客户端测试
├── test_k8s_deployer.py # K8s 部署器测试
├── test_deployment_agent.py # 部署 Agent 测试
└── test_config_loader.py # 配置加载器测试

运行测试

终端命令
# 运行所有测试
pytest tests/

# 显示覆盖率
pytest --cov=src tests/

# 运行特定测试文件
pytest tests/test_kubesphere_client.py -v

# 运行特定测试用例
pytest tests/test_kubesphere_client.py::TestKubeSphereClient::test_health_check

代码质量检查

终端命令
# 代码格式化检查
black --check src/ tests/

# 代码风格检查
flake8 src/ tests/

# 类型检查
mypy src/

项目文件列表

项目结构
k8s_deploy_agent/
├── src/
│ ├── __init__.py # 包初始化
│ ├── kubesphere_client.py # KubeSphere API 客户端
│ ├── k8s_deployer.py # K8s 集群部署器
│ ├── deployment_agent.py # 部署 Agent 主控制器
│ └── config_loader.py # 配置加载器

├── tests/
│ ├── __init__.py
│ ├── test_kubesphere_client.py
│ ├── test_k8s_deployer.py
│ ├── test_deployment_agent.py
│ └── test_config_loader.py

├── config/
│ └── config.yaml.example # YAML 配置示例

├── docs/
│ ├── 01_system_architecture.md # 系统架构文档
│ ├── 02_product_specification.md # 产品说明文档
│ └── 03_project_guide.md # 项目说明文档

├── .env.example # 环境变量示例
├── requirements.txt # Python 依赖
└── README.md # 项目 README