🔴 Advanced

AI in DevOps — Umelá inteligencia v DevOps

Umelá inteligencia mení spôsob, akým budujeme, nasadzujeme a prevádzkujeme softvér. Od AI-asistovaného kódovania cez inteligentný monitoring po automatickú remediáciu — AI sa stáva neoddeliteľnou súčasťou DevOps toolchainu.


AIOps — AI pre IT operácie

AIOps (Artificial Intelligence for IT Operations) je použitie strojového učenia na automatizáciu a zlepšenie IT operácií. Gartner tento termín definoval v 2017, no až s nástupom LLM sa stal prakticky použiteľným.

Čo AIOps rieši

  • Alert fatigue — tímy dostávajú stovky alertov denne, väčšina je šum
  • Root cause analysis — nájdenie príčiny v komplexnom systéme trvá hodiny
  • Capacity planning — predikcia zdrojov na základe trendov
  • Anomaly detection — odhalenie nezvyčajného správania pred výpadkom

AIOps pipeline

┌──────────┐    ┌───────────┐    ┌──────────┐    ┌──────────┐
│  Data     │──►│  Analyze   │──►│  Decide   │──►│  Act      │
│  Sources  │    │  (ML/AI)   │    │           │    │           │
│           │    │            │    │           │    │           │
│ • Logs    │    │ • Anomaly  │    │ • Alert   │    │ • Scale   │
│ • Metrics │    │   detection│    │ • Suppress│    │ • Restart │
│ • Traces  │    │ • Correlate│    │ • Escalate│    │ • Rollback│
│ • Events  │    │ • Predict  │    │ • Group   │    │ • Notify  │
└──────────┘    └───────────┘    └──────────┘    └──────────┘

AI Code Review

AI nástroje dokážu automaticky reviewovať pull requesty a odhaľovať problémy, ktoré ľudia prehliadnu.

Čo AI code review zachytí

  • Security vulnerabilities — SQL injection, XSS, hardcoded secrets
  • Performance issues — N+1 queries, memory leaks
  • Code quality — complexity, duplicity, naming
  • Best practices — error handling, logging, testing
  • Documentation gaps — chýbajúce komentáre, JSDoc

Nástroje pre AI code review

# GitHub Actions: AI code review
name: AI Code Review
on: [pull_request]

jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: AI Review
        uses: coderabbitai/ai-pr-reviewer@latest
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
        with:
          review_comment_lgtm: false
          summarize: true
          path_filters: |
            !**/*.lock
            !**/*.min.js

Vlastný AI review s LLM

import openai
import subprocess

def review_diff(diff: str) -> str:
    response = openai.chat.completions.create(
        model="gpt-4o",
        messages=[
            {"role": "system", "content": """Si senior DevOps engineer.
            Analyzuj git diff a identifikuj:
            1. Security problémy
            2. Performance problémy
            3. Infrastructure best practices
            4. Chýbajúce testy
            Buď konkrétny a navrhni riešenia."""},
            {"role": "user", "content": f"Review tento diff:\n\n{diff}"}
        ]
    )
    return response.choices[0].message.content

# Získanie diff-u z PR
diff = subprocess.check_output(
    ["git", "diff", "origin/main...HEAD"],
    text=True
)
review = review_diff(diff)
print(review)

Copilot v CI/CD

GitHub Copilot a podobné nástroje pomáhajú nielen s kódom, ale aj s CI/CD konfiguráciou.

Generovanie pipeline konfigurácií

AI dokáže generovať:

  • GitHub Actions workflows — z popisu požiadaviek
  • Dockerfile — optimalizovaný pre konkrétny stack
  • Kubernetes manifesty — deployment, service, ingress
  • Terraform moduly — infraštruktúra z popisu
  • Helm values — konfigurácia pre deployment

Copilot pre Infrastructure as Code

# Prompt: "AWS ECS Fargate cluster s ALB a auto-scaling"
# Copilot vygeneruje:

resource "aws_ecs_cluster" "main" {
  name = "production"

  setting {
    name  = "containerInsights"
    value = "enabled"
  }
}

resource "aws_ecs_service" "api" {
  name            = "api"
  cluster         = aws_ecs_cluster.main.id
  task_definition = aws_ecs_task_definition.api.arn
  desired_count   = 3
  launch_type     = "FARGATE"

  load_balancer {
    target_group_arn = aws_lb_target_group.api.arn
    container_name   = "api"
    container_port   = 8080
  }

  network_configuration {
    subnets         = var.private_subnets
    security_groups = [aws_security_group.ecs.id]
  }
}

resource "aws_appautoscaling_target" "api" {
  max_capacity       = 10
  min_capacity       = 2
  resource_id        = "service/${aws_ecs_cluster.main.name}/${aws_ecs_service.api.name}"
  scalable_dimension = "ecs:service:DesiredCount"
  service_namespace  = "ecs"
}

Intelligent Alerting

Tradičné alertovanie je založené na statických prahoch — "ak CPU > 80 %, pošli alert". AI prináša inteligentnejší prístup.

Anomaly detection

# Prometheus + ML anomaly detection
# Namiesto statického prahu:
- alert: HighCPU
  expr: cpu_usage > 80  # ❌ Statický prah

# AI-based anomaly detection:
- alert: AnomalousCPU
  expr: |
    abs(cpu_usage - predict_linear(cpu_usage[1h], 3600))
    > 3 * stddev_over_time(cpu_usage[7d])  # ✅ Dynamický

Alert correlation a grouping

AI dokáže korelovať zdanlivo nesúvisiace alerty:

Tradičné alertovanie:          AI alertovanie:
                               
Alert: High CPU (app-1)        Incident: Database overload
Alert: High latency (app-2)    ├─ Root cause: Slow DB queries
Alert: Connection pool full     ├─ Affected: app-1, app-2, app-3
Alert: 5xx errors (app-3)      ├─ Impact: 15% error rate
Alert: Queue backing up         └─ Suggested fix: Scale DB read replicas
                               
→ 5 alertov, 5 notifikácií     → 1 incident, 1 notifikácia

Noise reduction

# Príklad: AI-powered alert grouping
from sklearn.cluster import DBSCAN
import numpy as np

def group_alerts(alerts):
    """Zoskupí súvisiace alerty na základe času a služby."""
    features = np.array([
        [a['timestamp'], hash(a['service']) % 1000, hash(a['type']) % 100]
        for a in alerts
    ])

    clustering = DBSCAN(eps=60, min_samples=2).fit(features)

    groups = {}
    for i, label in enumerate(clustering.labels_):
        if label not in groups:
            groups[label] = []
        groups[label].append(alerts[i])

    return groups

Auto-Remediation

Auto-remediation je automatická oprava bežných problémov bez ľudského zásahu.

Príklady auto-remediation

# PagerDuty + Rundeck auto-remediation
triggers:
  - alert: DiskSpaceLow
    condition: disk_usage > 90%
    actions:
      - name: Clean Docker images
        command: docker system prune -af --filter "until=48h"
      - name: Clean logs
        command: find /var/log -name "*.log" -mtime +7 -delete
      - name: Notify team
        channel: "#ops"
        message: "Auto-cleaned disk on {{ .host }}"

  - alert: PodCrashLooping
    condition: restart_count > 5 in 10min
    actions:
      - name: Capture logs
        command: kubectl logs {{ .pod }} --previous > /tmp/crash-{{ .pod }}.log
      - name: Rollback deployment
        command: kubectl rollout undo deployment/{{ .deployment }}
      - name: Create incident
        severity: P2

Kubernetes Event-Driven Autoscaling (KEDA)

apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
  name: api-scaler
spec:
  scaleTargetRef:
    name: api-deployment
  minReplicaCount: 2
  maxReplicaCount: 20
  triggers:
    - type: prometheus
      metadata:
        serverAddress: http://prometheus:9090
        query: |
          sum(rate(http_requests_total{service="api"}[2m]))
        threshold: "100"
    - type: cpu
      metadata:
        type: Utilization
        value: "70"

AI pre Incident Response

AI-asistovaný troubleshooting

# CLI nástroj s AI pre diagnostiku
$ k8s-gpt analyze

[WARNING] Pod api-server-abc123 is in CrashLoopBackOff
  Root cause: OOMKilled - container exceeded memory limit (512Mi)
  Recent change: Deployment updated 30 min ago (+200MB memory usage)
  Recommendation:
  1. Increase memory limit: kubectl set resources deploy/api-server --limits=memory=1Gi
  2. Investigate memory leak in recent commit abc1234
  3. Add memory profiling to CI pipeline

[INFO] Node worker-3 has high memory pressure
  Cause: 15 pods scheduled, node capacity 85% utilized
  Recommendation: Consider adding nodes or using pod disruption budgets

Bezpečnosť AI v DevOps

Riziká

  • Hallucinations — AI môže generovať nesprávny kód/konfiguráciu
  • Secret leaking — AI modely trénované na verejnom kóde
  • Over-reliance — slepá dôvera v AI výstupy
  • Supply chain — AI-generované závislosti môžu byť škodlivé

Opatrenia

# AI-generated code safeguards
ai_review_policy:
  # Vždy vyžadovať ľudský review pre:
  require_human_review:
    - security-critical paths
    - infrastructure changes
    - database migrations
    - authentication/authorization

  # AI môže auto-approve:
  ai_auto_approve:
    - documentation updates
    - test additions
    - dependency bumps (patch only)
    - formatting changes

Nástroje v ekosystéme

Kategória Nástroje
AI Code Review CodeRabbit, Sourcery, Amazon CodeGuru
AI Coding GitHub Copilot, Cursor, Cline
AIOps Datadog AI, Dynatrace Davis, BigPanda
Intelligent Alerting PagerDuty AIOps, Moogsoft
Auto-remediation Shoreline, Rundeck, StackStorm
K8s AI K8sGPT, Kubecost

Best Practices

  1. AI je asistent, nie rozhodovateľ — vždy human-in-the-loop pre kritické operácie
  2. Začnite s observability — AI potrebuje dáta, investujte do metrics/logs/traces
  3. Postupná automatizácia — najprv suggest, potom auto-approve, potom auto-fix
  4. Validujte AI výstupy — testy, linting, security scan na AI-generovaný kód
  5. Merajte ROI — sledujte MTTR, alert noise reduction, deployment frequency

AI v DevOps nie je budúcnosť — je to prítomnosť. Od code review cez intelligent alerting po auto-remediation, AI nástroje dramaticky zlepšujú produktivitu tímov a spoľahlivosť systémov. Kľúčom je použiť AI ako multiplikátor ľudských schopností, nie ich náhradu.