Разработка AI-системы генерации Kubernetes YAML
AI-генерация Kubernetes манифестов — создание Deployment, Service, Ingress, HPA и других ресурсов на основе параметров приложения. Снижает ошибки в boilerplate конфигурациях и ускоряет onboarding новых сервисов.
Генерация полного набора манифестов
def generate_k8s_deployment(app: AppSpec) -> K8sManifests:
prompt = f"""Создай Kubernetes манифесты для приложения.
Параметры:
- Название: {app.name}
- Image: {app.image}:{app.tag}
- Порт: {app.port}
- Минимум реплик: {app.min_replicas}
- Максимум реплик: {app.max_replicas}
- CPU request/limit: {app.cpu_request}/{app.cpu_limit}
- Memory request/limit: {app.memory_request}/{app.memory_limit}
- Переменные окружения: {app.env_vars}
- Health check path: {app.health_path}
- Нужен PVC: {app.needs_storage}
Создай: Deployment, Service (ClusterIP), HorizontalPodAutoscaler,
PodDisruptionBudget (minAvailable=1), NetworkPolicy.
Best practices: resource limits, liveness/readiness probes, non-root user, read-only filesystem где возможно."""
raw = llm.generate(prompt, max_tokens=4000)
return parse_and_validate_manifests(raw)
Шаблоны для типовых сервисов
# AI-сгенерированный шаблон для stateless web service
apiVersion: apps/v1
kind: Deployment
metadata:
name: {{ app_name }}
labels:
app: {{ app_name }}
version: {{ version }}
spec:
replicas: {{ min_replicas }}
selector:
matchLabels:
app: {{ app_name }}
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1
maxUnavailable: 0 # zero-downtime
template:
spec:
securityContext:
runAsNonRoot: true
runAsUser: 1000
containers:
- name: {{ app_name }}
image: {{ image }}:{{ tag }}
ports:
- containerPort: {{ port }}
resources:
requests:
cpu: {{ cpu_request }}
memory: {{ memory_request }}
limits:
cpu: {{ cpu_limit }}
memory: {{ memory_limit }}
readinessProbe:
httpGet:
path: {{ health_path }}
port: {{ port }}
initialDelaySeconds: 10
periodSeconds: 5
livenessProbe:
httpGet:
path: {{ health_path }}
port: {{ port }}
initialDelaySeconds: 30
periodSeconds: 15
failureThreshold: 3
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
volumeMounts:
- name: tmp
mountPath: /tmp
volumes:
- name: tmp
emptyDir: {}
Валидация и security scanning
def validate_manifests(yaml_content: str) -> ValidationReport:
# kubeval — схема валидация
result = subprocess.run(
["kubeval", "--strict", "-"],
input=yaml_content.encode(),
capture_output=True
)
# kube-score — best practices
score_result = subprocess.run(
["kube-score", "score", "-"],
input=yaml_content.encode(),
capture_output=True, text=True
)
# checkov — security policies
checkov_result = subprocess.run(
["checkov", "-d", "/tmp/manifests", "--framework", "kubernetes", "-o", "json"],
capture_output=True, text=True
)
return ValidationReport(
schema_valid=result.returncode == 0,
score_issues=parse_kube_score(score_result.stdout),
security_failures=[c for c in json.loads(checkov_result.stdout)
if c["result"] == "FAILED" and c["severity"] in ["HIGH", "CRITICAL"]]
)
Автоматический PR с манифестами
После генерации и валидации — автоматический PR в GitOps репозиторий (ArgoCD/Flux):
def create_manifest_pr(app: AppSpec, manifests: K8sManifests, repo: GitRepo):
branch = f"feat/add-{app.name}-manifests"
repo.create_branch(branch)
for name, content in manifests.items():
repo.write_file(f"apps/{app.name}/{name}.yaml", content, branch)
pr = repo.create_pull_request(
title=f"Add Kubernetes manifests for {app.name}",
body=f"Auto-generated manifests for {app.name} v{app.tag}\n\nValidation: {manifests.validation_summary}",
branch=branch,
base="main"
)
return pr.url







